WPF中如何優雅的實現INotifyPropertyChanged介面
阿新 • • 發佈:2021-08-21
我用的比較多的框架是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 = nullView Code) 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>(refT 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 }View Code