x:Bind DependencyProperty 不工作(经典绑定工作正常)

x:Bind to DependencyProperty not working (classic Binding works fine)

我在将我的经典绑定移植到 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}"/>

编译器没有给我错误,所以它在构建应用程序时确实找到了目标 属性,但在运行时它就是不起作用。

我想我在这里遗漏了一些非常明显和愚蠢的东西,但我只是不知道它到底是什么。预先感谢您的帮助!

"classic" 绑定与最新编译的绑定 (x:Bind) 之间最烦人的区别是默认绑定模式。对于经典绑定,默认值为 OneWay,但对于 x:Bind,默认值为 OneTime,因此当您更改 属性 值时,它不会反映在 UI 因为绑定只获取一次值,并不关心任何未来的更改通知。

Value="{x:Bind ViewModel.MyValue, Mode=OneWay}"