BindableProperty通知属性已更改
本文关键字:属性 通知 BindableProperty | 更新日期: 2023-09-27 17:58:04
在自定义ContentView
上,我创建了一个类似的BindableProperty
public static readonly BindableProperty StrokeColorProperty =
BindableProperty.Create("StrokeColor",
typeof(Color),
typeof(SignaturePadView),
Color.Black,
BindingMode.TwoWay);
但我必须在属性更改时通知,因为我必须在自定义呈现器中读取属性,我该如何做到这一点
如果我在PropertyChanged
上为BindableProperty
设置它,它是一个静态方法,所以我不能这样做:(
BindingPropertyChangedDelegate<in TPropertyType>(BindableObject bindable, TPropertyType oldValue, TPropertyType newValue);
正如您所看到的,第一个输入参数将是BindableObject。您可以安全地将bindable强制转换到自定义类中,并获取属性已更改的实例。像这样:
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
});
这显示了在标记特性的共享代码中捕捉特性更改的正确方法。如果您在本机项目中有一个自定义渲染器,则它的OnElementPropertyChanged事件将激发,并将"StrokeColor"作为PropertyName,无论是否将此propertyChanged委托提供给BindableProperty定义。
在渲染器上覆盖OnElementPropertyChanged
方法:
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if(e.PropertyName=="StrokeColor")
DoSomething();
}