您显示的代码将调用事件委托的次数与SendPropertyChanged
调用次数相同。这里没有魔法。但是,一种常见的方法(在您未显示的代码中返回一个级别)是检查实际更改,例如:
private int id;
public int Id {
get { return id; }
set {
if(id != value) {
id = value;
SendPropertyChanged(); // let C# 5 compiler tricks supply the name
}
}
}
private void SendPropertyChanged([CallerMemberName]string propertyName = null)
{
var handler = PropertyChanged;
if(handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
带测试:
var obj = new Foo();
int count = 0;
obj.PropertyChanged += delegate { count++; };
obj.Id = 1;
obj.Id = 2;
obj.Id = 3;
Console.WriteLine(count); // outputs: 3
count = 0;
obj.Id = 1;
obj.Id = 1;
obj.Id = 1;
Console.WriteLine(count); // outputs: 1