我正在将我的经典绑定移植到UWP应用程序中的新编译绑定时遇到一些问题。
我有一个带有简单DependencyProperty
的用户控件:
public double Value
{
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register(nameof(Value), typeof(double), typeof(MyUserControl),
new PropertyMetadata(0d, OnValuePropertyChanged));
private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Get the new value and do stuff on the control
}
在我的页面代码后台文件中,我为DataContext分配了一个值,并创建了一个已编译绑定的参数:
public MyPage()
{
this.InitializeComponent();
DataContext = new MyPageViewModel();
}
public MyPageViewModel ViewModel => (MyPageViewModel)DataContext;
现在这个经典的绑定方式有效(目标参数已经正确实现了INotifyPropertyChanged接口):
<controls:MyUserControl Value="{Binding MyValue}"/>
但是这个编译绑定不会:
<controls:MyUserControl Value="{x:Bind ViewModel.MyValue}"/>
编译器没有报错,所以在构建应用程序时它确实找到了目标属性,但在运行时却无效。我猜我可能漏掉了一个非常明显和愚蠢的东西,但我不确定具体是什么。提前感谢你的帮助!