Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :(

like image 634
Lasse Madsen Avatar asked Jul 21 '16 07:07

Lasse Madsen


1 Answers

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.

like image 160
irreal Avatar answered Oct 09 '22 03:10

irreal