Xamarin.Forms如何在代码中添加行为

时间:2015-07-30 12:02:55

标签: xamarin xamarin.forms behavior

我想要实现的是将Entry字段的输入限制为通过代码而不是XAML的两个字符

这可以通过以下方式在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;

    }
}

1 个答案:

答案 0 :(得分:4)

entry.Behaviors.Add(new MaxLengthValidator { MaxLength = 2 });