该
INotifyPropertyChanged接口 是
与事件实现。该界面只有一个成员,
PropertyChanged这是消费者可以订阅的事件。
理查德发布的版本不安全。以下是安全实现此接口的方法:
public class MyClass : INotifyPropertyChanged{ private string imageFullPath; protected void onPropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, e); } protected void onPropertyChanged(string propertyName) { onPropertyChanged(new PropertyChangedEventArgs(propertyName)); } public string ImageFullPath { get { return imageFullPath; } set { if (value != imageFullPath) { imageFullPath = value; onPropertyChanged("ImageFullPath"); } } } public event PropertyChangedEventHandler PropertyChanged;}请注意,这将执行以下操作:
抽象属性更改通知方法,以便您可以轻松地将其应用于其他属性;
在 尝试调用
PropertyChanged
代理 之前,先 制作该代理的副本(否则,将创建竞争条件)。正确实现
INotifyPropertyChanged
接口。
如果要为更改的 特定 属性 另外 创建通知,则可以添加以下代码: __
protected void onImageFullPathChanged(EventArgs e){ EventHandler handler = ImageFullPathChanged; if (handler != null) handler(this, e);}public event EventHandler ImageFullPathChanged;然后在该行
onImageFullPathChanged(EventArgs.Empty)之后添加该行
onPropertyChanged("ImageFullPath")。由于我们有.Net 4.5,因此存在
CallerMemberAttribute,它可以摆脱源代码中属性名称的硬编码字符串:
protected void onPropertyChanged( [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "") { onPropertyChanged(new PropertyChangedEventArgs(propertyName)); } public string ImageFullPath { get { return imageFullPath; } set { if (value != imageFullPath) { imageFullPath = value; onPropertyChanged(); } } }


