Chad Bonthuys
Chad Bonthuys

Reputation: 2039

Xamarin.Forms How to add Behaviors in code

What I am trying to achieve is limiting the input of an Entry field to two character via code and not XAML

This can be achieved in XAML using the below:

<Entry.Behaviors>
        <local:NumberValidatorBehavior x:Name="ageValidator" />
        <local:MaxLengthValidator  MaxLength="2"/>

I assume I will need to do something like this but I'm not quite sure how to add the required behaviour property

entry.Behaviors.Add(new MyBehavior())

Edit Answer

After adding the MaxLengthValidator class listed below and calling it using the proposed method by @Rui Marinho my code is working as expected.

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;

    }
}

Upvotes: 2

Views: 3293

Answers (1)

Rui Marinho
Rui Marinho

Reputation: 1712

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

Upvotes: 4

Related Questions