gpt4 book ai didi

c# - UWP:替换数据绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 20:32:31 24 4
gpt4 key购买 nike

我有一个很奇怪的问题。如果我设置了绑定(bind)并将绑定(bind)更改为另一个属性,它将不起作用。

看看这个简单的例子

lblTotal.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("Subtotal"), Source = Order, Mode = BindingMode.OneWay });
lblTotal.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("FinalTotal"), Source = Order, Mode = BindingMode.OneWay });

FinalTotal 更改时,lblTotal 文本将NOT 更改。

现在,注释掉第一行。

//lblTotal.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("Subtotal"), Source = Order, Mode = BindingMode.OneWay });
lblTotal.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("FinalTotal"), Source = Order, Mode = BindingMode.OneWay });

现在成功了!!!!更改 FinalTotal 将更改 lblTotal 文本!知道为什么吗?

此外,BindingOperations.ClearBinding() 在 UWP 中不可用。所以我尝试用空绑定(bind)替换它,但它仍然不起作用。

lblTotal.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("Subtotal"), Source = Order, Mode = BindingMode.OneWay });

//remove binding - not sure if this is correct way to remove binding because
//BindingOperations.ClearBinding() isn't available in UWP!
BindingOperations.SetBinding(lblTotal, TextBlock.TextProperty, new Binding());

lblTotal.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("FinalTotal"), Source = Order, Mode = BindingMode.OneWay });

我的问题是:1.如何替换UWP中的绑定(bind)?2. 如何删除 UWP 中的现有绑定(bind)(即与 BindingOperations.ClearBinding() 等效的功能)?

感谢您的帮助...

最佳答案

正如在 FrameworkElement.SetBinding method 中声明的那样:

Note Calling the SetBinding method and passing in a new Binding object won't necessarily remove an existing binding. Instead, you should first call the DependencyObject.ClearValue method, then call SetBinding.

因此您可以像下面这样更改您的代码:

lblTotal.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("Subtotal"), Source = Order, Mode = BindingMode.OneWay });
lblTotal.ClearValue(TextBlock.TextProperty);
lblTotal.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("FinalTotal"), Source = Order, Mode = BindingMode.OneWay });

在此之后您的代码应该能够工作。更多信息,请参见FrameworkElement.SetBinding备注还有BindingOperations.SetBinding .

关于c# - UWP:替换数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41300099/

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