我有一个基类:
public class PersonBaseClass : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set
{
if (value != name)
{
name = value;
NotifyPropertyChanged("Name");
}
}
}
}
和派生类
public class TeacherClass : PersonBaseClass, INotifyPropertyChanged
{
private string id;
public string Id
{
get { return id; }
set
{
if (value != id)
{
id = value;
NotifyPropertyChanged("Id");
}
}
}
}
上面每个代码的末尾都有这个神奇的代码!
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
然后我在 xaml 列表中显示 Teachers
集合列表。现在,如果我更改 Id
,将为用户显示更改,但不会显示作为基类属性的 Name
的更改。在调试中,我看到设置 Name
值后,NotifyPropertyChanged
方法中的 handler
为 null,这似乎是问题所在。
如何解决基类的变化也出现在列表中?
最佳答案
只有 PersonBaseClass 实现 INotifyPropertyChanged 并将 NotifyPropertyChange 设置为 protected ,这样您就可以从子类中调用它。不需要执行两次。这也应该可以解决问题。
关于c# - 如何为派生类实现 INotifyPropertyChanged?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23577311/