我想为基类上的属性实现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")
,但我不确定如何将其引入基类。有什么想法吗?
答案 0 :(得分:2)
这就是你想要的吗?
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));
}
}
}
和儿童班:
public class PersonViewModel : ViewModelBase
{
public PersonViewModel()
{
base.HasChanged = true;
}
}