當TextBox
的Text
屬性綁定到該對象實現INotifyPropertyChanged
對象屬性,事件PropertyChanged
雖然具有相同的價值可能會閃光兩次: 1)當文本當控件離開它時,在TextBox
2)內被改變。文本框休假導致的PropertyChanged被解僱兩次
考慮一種形式的這些方法:
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"));
}
}
}
要重現該問題,鍵入一些在上文本框,檢查控制檯,然後進入下面的文本框並再次檢查控制檯。在離開時,報告財產變更。爲什麼?
因爲它必將 – DonBoitnott
邊界的確定。爲什麼更新源發生兩次? – Alireza