【发布时间】:2013-12-25 19:08:45
【问题描述】:
当TextBox 的Text 属性绑定到该对象实现INotifyPropertyChanged 的对象属性时,事件PropertyChanged 可能会触发两次,同时具有相同的值:
1) 当文本在TextBox 内改变时2) 当控件离开它时。
考虑一下表单的这些方法:
private void Form1_Load(object sender, EventArgs e)
{
TextBox textBox = new TextBox();
TextBox secondTextBox = new TextBox();
secondTextBox.Location = new Point(0, 100);
this.Controls.Add(textBox);
this.Controls.Add(secondTextBox);
MyClass instance = new MyClass();
instance.PropertyChanged += instance_PropertyChanged;
textBox.DataBindings.Add("Text", instance, "Id", true, DataSourceUpdateMode.OnPropertyChanged);
}
private void instance_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine(e.PropertyName + " changed");
}
和后端类:
private class MyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
int _id;
public int Id
{
get
{
return _id;
}
set
{
_id = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Id"));
}
}
}
要重现问题,请在上方文本框中输入内容,检查控制台,然后输入下方文本框并再次检查控制台。离开时,报告财产变化。为什么?
【问题讨论】:
-
边界正常。为什么要更新源两次?