Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 91519

Binding to Custom Behavior Bindable Property in XAML

$
0
0

I'm trying to follow along with the information here about making a custom max length behavior: https://xamarinhelp.com/xamarin-forms-triggers-behaviors-effects/

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;
    }
 }

But I'm kind of confused about how to bind to the new BindableProperty in XAML.

    // Add to Page attributes
    xmlns:behavior="clr-namespace:Mobile.Behavior"

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

I don't understand the part about the IsValid binding.

I am new to Xamarin.Forms and I'm still struggling with bindings a bit, and this is confusing me - it looks to me like maybe it's connecting with the entry text field in the source (with "x:Reference this"), but what is the "BindingContext.IsUsernameValid" supposed to represent?

I thought the BindingContext is the parent object and the binding should connect to the property/child of that object, but I don't understand how it's being used here with a behavior - what is that object supposed to be? There's no complete sample in GitHub, so I can't tell if that was supposed to be the "IsValid" property instead (there are other errors in here - see ">= MinLength"), or if I'm missing part of the code, or what.

I could use some help figuring out the correct structure of the binding and would really appreciate some clarification.


Viewing all articles
Browse latest Browse all 91519

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>