[英]Base class implements INotifyPropertyChanged : can derived types use its PropertyChanged event?
[英]inheritance base class implements interface INotifyPropertyChanged can child class make use of it
我有一个绑定到ObservableCollection的数据网格。 我想知道何时更改属性。 在同一个应用程序中,我有一个类似的数据网格。 但是,此数据网格已绑定到从另一个类继承的类。
因此,下面显示了一个简单的代码段。
在孩子中,我必须实现INotifyPropertyChanged接口,尽管这对我来说似乎有点痛苦,而且并没有真正利用继承。 我可以简单地仅公开OnPropertyChanged还是这样吗?
基类
class Animal : INotifyPropertyChanged
{
public int Age
{
get
{ return _age;}
set
{
_age = value;
OnPropertyChanged("Age");
}
}
int _age
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
儿童班
class Dog : Animal
{
public bool Fleas
{
get
{ return _fleas;}
set
{
_fleas = value;
}
}
int _fleas
}
protected
可能是您想要的,但通常是。
例如,在诸如Caliburn.Micro之类的MVVM框架中,您经常会发现有一件事,就是有一个类似PropertyChangedBase
的抽象类,它只有INotifyPropertyChanged
简单实现。
public abstract class PropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
这种方法的缺点是,最终要使用该类的所有类最终都必须继承PropertyChangedBase
,这可能并不总是需要或不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.