在很多地方需要用上INotifyPropertyChanged的接口,MVVM模式,List等集合都会用到。
通常我们使用
protected void OnChange(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args); private OutString _Text; public OutString Text { get => _Text; set { _Text = value; OnChange(new PropertyChangedEventArgs("Text")); } }
不过可以 使用特性来减少代码量
CallerMemberName可以代替手工输入名称
public class Test:INotifyPropertyChanged { protected void OnPropertyChanged([CallerMemberName] string name="") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } private BitmapImage i; public BitmapImage Image { get=>i; set { i = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; }