【发布时间】:2015-08-06 21:58:12
【问题描述】:
我想要实现的是通过代码而不是 XAML 将 Entry 字段的输入限制为两个字符
这可以通过以下方式在 XAML 中实现:
<Entry.Behaviors>
<local:NumberValidatorBehavior x:Name="ageValidator" />
<local:MaxLengthValidator MaxLength="2"/>
我假设我需要做这样的事情,但我不太确定如何添加所需的行为属性
entry.Behaviors.Add(new MyBehavior())
编辑答案
添加下面列出的 MaxLengthValidator 类并使用@Rui Marinho 建议的方法调用它后,我的代码按预期工作。
public class MaxLengthValidator : Behavior<Entry>
{
public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthValidator), 0);
public int MaxLength
{
get { return (int)GetValue(MaxLengthProperty); }
set { SetValue(MaxLengthProperty, value); }
}
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += bindable_TextChanged;
}
private void bindable_TextChanged(object sender, TextChangedEventArgs e)
{
if (e.NewTextValue.Length > 0 && e.NewTextValue.Length > MaxLength)
((Entry)sender).Text = e.NewTextValue.Substring(0, MaxLength);
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= bindable_TextChanged;
}
}
【问题讨论】:
标签: xamarin xamarin.forms behavior