简体   繁体   English

如何为派生类实现INotifyPropertyChanged?

[英]How to implement INotifyPropertyChanged for derived classes?

I have a base class: 我有一个基类:

public class PersonBaseClass : INotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            if (value != name)
            {
                name = value;
                NotifyPropertyChanged("Name");
            }
        }
    }
}

and a derived class 和派生类

public class TeacherClass : PersonBaseClass, INotifyPropertyChanged
{
    private string id;
    public string Id
    {
        get { return id; }
        set
        {
            if (value != id)
            {
                id = value;
                NotifyPropertyChanged("Id");
            }
        }
    }
}

and this magic code at the end of each one above! 而这个神奇的代码在每个上面的结尾!

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

Then I show a list of Teachers collection in a list in xaml. 然后我在xaml的列表中显示Teachers集合列表。 Now if I change Id , changes will appear for user, but changes in Name which is a property in base class doesn't appear. 现在,如果我更改Id ,将为用户显示更改,但不会显示作为基类属性的Name中的更改。 In debug, I see after setting Name value, the handler inside NotifyPropertyChanged method is null which seems it is the problem. 在调试中,我看到在设置Name值后, NotifyPropertyChanged方法内的handler为null,这似乎是问题所在。

How can I solve it to changes of base class also appear in the list? 如何解决基类更改也会出现在列表中?

Have only PersonBaseClass implementing INotifyPropertyChanged and make NotifyPropertyChange as protected so you can call it from child classes. 只有PersonBaseClass实现INotifyPropertyChanged并使NotifyPropertyChange成为受保护的,因此您可以从子类中调用它。 There is not need to implement it twice. 不需要两次实现它。 That should fix the problem as well. 这也应该解决问题。

Your "magic code" section should only be in PersonBaseClass. 您的“魔术代码”部分应该只在PersonBaseClass中。 You can make the NotifyPropertyChanged function protected so that the same function can be called from TeacherClass as well. 您可以使NotifyPropertyChanged函数受到保护,以便也可以从TeacherClass调用相同的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM