我有一个非常奇怪的问题。如果我已设置绑定并将绑定更改为另一个属性,则无法正常工作。
看看这个简单的例子
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文本!知道为什么吗?
此外,UWP中不提供 BindingOperations.ClearBinding()。所以我试图用空绑定替换它,它仍然不起作用。
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中的绑定? 2.如何删除UWP中的现有绑定(即等效函数为 BindingOperations.ClearBinding())?
感谢您的帮助......
答案 0 :(得分:4)
在FrameworkElement.SetBinding method中声明:
注意调用 SetBinding 方法并传入新的Binding对象不一定会删除现有绑定。相反,您应首先调用DependencyObject.ClearValue方法,然后调用 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的备注。