WPF 中数据绑定如何避免递归更新?
我正在研究 WPF 中的绑定,然后我有这个问题:
假设依赖属性绑定到实现 INotifyPropertyChanged 接口的对象的属性。
当绑定目标更新源时,源的属性也会更新。
由于源对象的属性设置器发生了变化,它会依次通知监听器-绑定目标,这将导致递归更新。
WPF 中如何避免这种情况?
I am studying binding in WPF, then I have this question:
let's say a dependency property is binded to a property of an object which implements INotifyPropertyChanged interface.
when the binding target update the source, then the source's property get updated.
since the property setter of the source object changed, it will in turn notify the listener-the binding target, which will result in recursive update.
How is this avoided in WPF?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由属性更改事件引起的源更新不会触发绑定,并且绑定更新源时发生的属性更改事件将被忽略。
这是演示这一点的简单方法。创建此类:
现在创建一个包含两个
TextBox
的窗口,其Text
绑定到此类实例上的Property
属性。使两者都使用双向绑定,并将UpdateSourceTrigger
设置为PropertyChanged
。每当您在任一绑定的
TextBox
中输入数字时,另一个TextBox
将显示下一个数字。第一个TextBox
上的绑定忽略源引发的PropertyChanged
事件,因为该事件是在绑定期间发生的。第二个文本框确实由第一个PropertyChanged
事件更新,但它不会用新值更新源。如果您在代码中更新属性(例如在按钮单击事件中),则两个 TextBox 将显示相同的值 - 例如,如果您将属性设置为 20,则两者都将显示 21。当属性设置为 20、显示当前值 21 并且绑定不更新源时,将触发 -changed 事件。
Updates to the source caused by a property-changed event don't trigger binding, and property-changed events that occur while a binding is updating the source are ignored.
Here's an easy way to demonstrate this. Create this class:
Now create a window containing two
TextBox
es whoseText
is bound to theProperty
property on an instance of this class. Make both use two-way binding, withUpdateSourceTrigger
set toPropertyChanged
.Whenever you type a number into the either bound
TextBox
, the otherTextBox
will display the next number. The binding on the firstTextBox
is ignoring thePropertyChanged
event that the source is raising because that event is happening during binding. The second text box does get updated by the firstPropertyChanged
event, but it doesn't update the source with its new value.If you update the property in code, (e.g. in a button-click event), both
TextBox
es will display the same value - e.g. if you set the property to 20, both will display 21. The property-changed event fires when the property is set to 20, the current value of 21 is displayed, and the bindings don't update the source.