c# - 如何为派生类实现 INotifyPropertyChanged?

标签 c# wpf xaml windows-phone-8 windows-runtime

我有一个基类:

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/

相关文章:

c# - SHA 计算随机长度的哈希值

c# - C# 和 VB 之间的 Visual Studio 2005 中的 Intellisense - 无法导航到定义

c# - System.Windows.Interactivity 必须在主项目中引用

wpf - 如何在 XAML 中获取容器(如 dll)中的特定图标?

xaml - 在 UWP 中保持 ListView.HeaderTemplate 可见/静态/粘性

xaml - 防止系统 FontSize 更改影响 Xamarin 应用程序中的大小

c# - WP中的MVVM和枢轴控制

c# - 使用外部 Web API 提供的 OAuth Bearer Token 进行授权

c# - 如何为复选框图像创建自定义 WPF XAML 样式

c# - WPF 中 TextBox 的 BorderThickness(错误?)