WPF中如何优雅的实现INotifyPropertyChanged接口
我用的比较多的框架是Prism,我们就可以借鉴一下Prism的INotifyPropertyChanged实现的源码
1 public abstract class BindableBase : INotifyPropertyChanged 2 { 3 public event PropertyChangedEventHandler PropertyChanged; 4 5 protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) 6 { 7 if (EqualityComparer<T>.Default.Equals(storage, value)) 8 { 9 return false; 10 } 11 storage = value; 12 RaisePropertyChanged(propertyName); 13 return true; 14 } 15 16 protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null) 17 { 18 if (EqualityComparer<T>.Default.Equals(storage, value)) 19 { 20 return false; 21 } 22 storage = value; 23 onChanged?.Invoke(); 24 RaisePropertyChanged(propertyName); 25 return true; 26 } 27 28 protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) 29 { 30 OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); 31 } 32 33 protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) 34 { 35 this.PropertyChanged?.Invoke(this, args); 36 } 37 }
怎么使用呢?其实很简单,继承一下BindableBase,然后就可以很简单的实现动态通知了
1 class Sample : BindableBase 2 { 3 private string name; 4 public string Name 5 { 6 get { return name; } 7 set { SetProperty(ref name, value); } 8 } 9 }