How does data binding avoid recursive update in 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 so开发者_运维知识库urce, 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?
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:
public class TestClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _Property;
public int Property
{
get { return _Property; }
set
{
if (value < 1000) // just to be on the safe side
{
_Property = value + 1;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Property"));
}
}
}
}
}
Now create a window containing two TextBox
es whose Text
is bound to the Property
property on an instance of this class. Make both use two-way binding, with UpdateSourceTrigger
set to PropertyChanged
.
Whenever you type a number into the either bound TextBox
, the other TextBox
will display the next number. The binding on the first TextBox
is ignoring the PropertyChanged
event that the source is raising because that event is happening during binding. The second text box does get updated by the first PropertyChanged
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.
精彩评论