wpf 实现INotifyPropertyChanged

示例

INotifyPropertyChanged是绑定源(即DataContext)使用的接口,以使用户界面或其他组件知道属性已更改。WPF在看到PropertyChanged事件引发时会自动为您更新UI 。最好在所有视图模型都可以继承的基类上实现此接口。

在C#6中,这就是您所需要的:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

这使您可以通过NotifyPropertyChanged两种不同的方式进行调用:

  1. NotifyPropertyChanged(),这要归功于调用它的setter的事件,这要归功于CallerMemberName属性。

  2. NotifyPropertyChanged(nameof(SomeOtherProperty)),这将引发SomeOtherProperty的事件。

对于使用C#5.0的.NET 4.5及更高版本,可以代替使用:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged([CallerMemberName] string name = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

在4.5之前的.NET版本中,必须将属性名称设置为字符串常量或使用表达式的解决方案。


注意:可以绑定到未实现的“普通C#对象”(POCO)的属性,INotifyPropertyChanged并观察到绑定的工作比预期的要好。这是.NET中的隐藏功能,应避免使用。特别是因为它会导致内存泄漏时绑定的Mode不是OneTime(见这里)。

为什么在不实现INotifyPropertyChanged的情况下进行绑定更新?