如何为派生类实现INotifyPropertyChanged?

use*_*835 2 c# wpf xaml windows-runtime windows-phone-8

我有一个基类:

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

和派生类

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

而这个神奇的代码在每个上面的结尾!

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

然后我Teachers在xaml的列表中显示集合列表.现在,如果我更改Id,将为用户显示更改,但Name不会显示基类中的属性更改.在调试中,我看到在设置Name值之后,handlerinside NotifyPropertyChanged方法为null,这似乎是问题所在.

如何解决基类更改也会出现在列表中?

raz*_*akj 7

只有PersonBaseClass实现INotifyPropertyChanged并使NotifyPropertyChange成为受保护的,因此您可以从子类中调用它.不需要两次实现它.这也应该解决问题.