继承基类实现接口INotifyPropertyChanged可以让子类使用它

时间:2016-01-12 16:43:03

标签: c# .net wpf

我有一个绑定到ObservableCollection的数据网格。我想知道什么时候改变房产。我在同一个应用程序中有一个类似的数据网格,我有这个工作。但是,此datagrid绑定到一个继承自另一个类的类。

下面是一个简单的代码片段。

在孩子中我是否必须实现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

}

1 个答案:

答案 0 :(得分:5)

protected可能就是你想要的,但一般来说,是的。

您经常发现的一件事,例如在MVVM框架(如Caliburn.Micro)中,有一个像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,这可能并不总是希望或可能的。