Lasse Madsen
Lasse Madsen

Reputation: 602

BindableProperty notify property changed

On a custom ContentView I have created a BindableProperty like this

public static readonly BindableProperty StrokeColorProperty = 
    BindableProperty.Create("StrokeColor", 
                            typeof(Color), 
                            typeof(SignaturePadView), 
                            Color.Black, 
                            BindingMode.TwoWay);

But I have to notify on property change, as I have to read the property in a custom Renderer, how can I do this?
If I set it on the PropertyChanged for BindableProperty it is a static method, so I can not take it from that way :(

Upvotes: 6

Views: 10222

Answers (2)

irreal
irreal

Reputation: 2296

The PropertyChanged event handler for the BindableProperty will indeed be static, but the input parameters on it are

BindingPropertyChangedDelegate<in TPropertyType>(BindableObject bindable, TPropertyType oldValue, TPropertyType newValue);

so as you can see, the first input parameter will be a BindableObject. You can safely cast bindable into your custom class and get the instance who's property has changed. like this:

public static readonly BindableProperty StrokeColorProperty = 
    BindableProperty.Create("StrokeColor", 
                            typeof(Color), 
                            typeof(SignaturePadView), 
                            Color.Black, 
                            BindingMode.TwoWay,
propertyChanged: (b, o, n) =>
                {
                    var spv = (SignaturePadView)b;
                    //do something with spv
                    //o is the old value of the property
                    //n is the new value
                });

This shows the correct way to catch the property change in shared code where the property is decalred. If you have a custom renderer in the native project, it's OnElementPropertyChanged event will fire, with "StrokeColor" as the PropertyName, with or without this propertyChanged delegate being supplied to the BindableProperty definition.

Upvotes: 13

eakgul
eakgul

Reputation: 3698

Override OnElementPropertyChanged method on your Renderer:

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if(e.PropertyName=="StrokeColor")
            DoSomething();
    }

Upvotes: 1

Related Questions