在自定义 ContentView
上,我创建了一个 BindableProperty
,如下所示
public static readonly BindableProperty StrokeColorProperty =
BindableProperty.Create("StrokeColor",
typeof(Color),
typeof(SignaturePadView),
Color.Black,
BindingMode.TwoWay);
但是我必须通知属性更改,因为我必须在自定义渲染器中读取属性,我该怎么做?
如果我在 BindableProperty
的 PropertyChanged
上设置它,它是一个静态方法,所以我不能从那种方式获取它:(
最佳答案
BindableProperty 的 PropertyChanged 事件处理程序确实是静态的,但它的输入参数是
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
});
这显示了在标记属性的共享代码中捕获属性更改的正确方法。如果您在 native 项目中有自定义渲染器,它的 OnElementPropertyChanged 事件将触发,将“StrokeColor”作为 PropertyName,无论是否将此 propertyChanged 委托(delegate)提供给 BindableProperty 定义。
关于c# - BindableProperty 通知属性改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38498152/