【问题标题】:inheritance base class implements interface INotifyPropertyChanged can child class make use of it继承基类实现接口 INotifyPropertyChanged 子类可以使用
【发布时间】:2016-01-13 00:54:33
【问题描述】:

我有一个绑定到 ObservableCollection 的数据网格。我想知道何时更改属性。我有一个类似的数据网格在我有这个工作的同一个应用程序中。但是,此数据网格绑定到从另一个类继承的类。

所以一个简单的代码sn-p如下所示。

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

}

【问题讨论】:

  • 您的代码中没有显示继承...您没有包括什么?
  • 抱歉狗应该是从动物继承的——更新了我的代码

标签: c# .net wpf


【解决方案1】:

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 继承,这可能并不总是需要或可能的。

【讨论】:

    猜你喜欢
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 2019-08-04
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    相关资源
    最近更新 更多