WPF – 为基类实现System.ComponentModel.INotifyPropertyChanged

我想为基类上的属性实现System.ComponentModel.INotifyPropertyChanged接口,但我不太清楚如何连接它。

这是我想收到通知的属性的签名:

public abstract bool HasChanged(); 

我的基类中的代码用于处理更改:

 public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(String info) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(info)); } } 

如何在基类中处理事件的连接而不必在每个子类中调用OnPropertyChanged()?

谢谢,
桑尼

编辑:好的…所以我认为当HasChanged()的值发生变化时,我应该调用OnPropertyChanged("HasChanged") ,但我不确定如何将它导入基类。 有任何想法吗?

这就是你追求的吗?

 public abstract class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; //make it protected, so it is accessible from Child classes protected void OnPropertyChanged(String info) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(info)); } } } 

请注意,OnPropertyChanged可访问级别受到保护。 然后在您的具体课程或子课程中,您可以:

 public class PersonViewModel : ViewModelBase { public PersonViewModel(Person person) { this.person = person; } public string Name { get { return this.person.Name; } set { this.person.Name = value; OnPropertyChanged("Name"); } } } 

编辑:再次阅读OP问题后,我意识到他不想在子类中调用OnPropertyChanged ,所以我很确定这会起作用:

 public abstract class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private bool hasChanged = false; public bool HasChanged { get { return this.hasChanged; } set { this.hasChanged = value; OnPropertyChanged("HasChanged"); } } //make it protected, so it is accessible from Child classes protected void OnPropertyChanged(String info) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(info)); } } } 

在儿童class:

 public class PersonViewModel : ViewModelBase { public PersonViewModel() { base.HasChanged = true; } }