gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:50:14 32 4
gpt4 key购买 nike

我在将我的经典绑定(bind)移植到 UWP 应用中的新编译绑定(bind)时遇到了一些问题。

我有一个带有简单 DependencyProperty 的 UserControl:

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 并为编译绑定(bind)创建了一个参数:

public MyPage()
{
this.InitializeComponent();
DataContext = new MyPageViewModel();
}

public MyPageViewModel ViewModel => (MyPageViewModel)DataContext;

现在,这个经典绑定(bind)有效(目标参数正确实现了 INotifyPropertyChanged 接口(interface)):

<controls:MyUserControl Value="{Binding MyValue}"/>

但是这个编译绑定(bind)不会:

<controls:MyUserControl Value="{x:Bind ViewModel.MyValue}"/>

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

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

最佳答案

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

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

关于c# - x :Bind to DependencyProperty not working (classic Binding works fine),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33084142/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com