Behaviors in Xamarin Forms

In Mobile Development by Christian HissibiniLeave a Comment

Behaviors allow you to enhance the functionality of a Xamarin Forms control without sub classing. Using the Behaviors property you can add behaviors that attached to the Control and can execute code when events of that control are raised.

Documentation: Introduction to Behaviors

Example Use Case: Apply validation rules to an Entry control.

Here is an example of applying a maximum length validator to an Entry Control. First we create a behavior.

public class MaxLengthCheckValidator: Behavior<Entry>

    public static readonly BindableProperty IsValidProperty = BindableProperty.Create("IsValid", typeof(bool), typeof(MaxLengthCheckValidator), false);
    public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthCheckValidator), 0);

    public int MaxLength
       get { return (int)GetValue(MaxLengthProperty); }
       set { SetValue(MaxLengthProperty, value); }

    public bool IsValid
       get { return (bool)GetValue(IsValidProperty); }
       set { SetValue(IsValidProperty, value); }

    protected override void OnAttachedTo(Entry bindable)
       bindable.TextChanged += bindable_TextChanged;

    private void bindable_TextChanged(object sender, TextChangedEventArgs e)
       IsValid = e.NewTextValue?.Length >= MinLength;

    protected override void OnDetachingFrom(Entry bindable)
       bindable.TextChanged -= bindable_TextChanged;

Then we apply it to an entry control. We can use the IsValid property to bind to something just as a Button IsEnabled Property or similar to stop users from progressing forward without meeting the forms requirements.

// Add to Page attributes

<Entry Text="{Binding EntryField}">
        <behavior:MaxLengthCheckValidator MaxLength="10" IsValid="{Binding Source={x:Reference this}, BindingContext.IsUsernameValid, Mode=OneWayToSource}" />

Ref – –

Leave a Comment