通常情况下,这种问题是因为没有正确地设置绑定路径或没有在绑定目标上启用属性更改通知。示例代码如下:
public static readonly BindableProperty TestProperty =
BindableProperty.Create("Test", typeof(string), typeof(MyControl), null, propertyChanged: OnTestPropertyChanged);
public string Test
{
get { return (string)GetValue(TestProperty); }
set { SetValue(TestProperty, value); }
}
private static void OnTestPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
// Perform some action when the Test property is changed
}
在这个示例中,绑定目标需要启用属性更改通知。可以使用 INotifyPropertyChanged 接口或 Xamarin.Forms 中内置的 PropertyChangedBase 类来实现这一点:
public class MyViewModel : PropertyChangedBase
{
private string _test;
public string Test
{
get { return _test; }
set { SetProperty(ref _test, value); }
}
}
此外,还要确保在绑定路径中正确地引用了属性。例如,如果要绑定到视图模型中的 Test 属性,绑定路径应为“{Binding Test}”。