C# 【WPF】之 INotifyPropertyChanged的简单封装

以下是一个简单的 INotifyPropertyChanged 封装示例:

using System.ComponentModel;
c#兼职Q群:741058172
public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
  protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    protected bool SetProperty<T>(ref T storage, T value, string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return false;
        }

        storage = value;
        RaisePropertyChanged(propertyName);
        return true;
    }
}

使用这个封装,你可以在你的 ViewModel 类中继承 ObservableObject 类,以获得 INotifyPropertyChanged 的支持。你只需要在定义属性时使用 SetProperty 方法来设置属性,如下所示:

private string _name;
public string Name
{
    get => _name;
    set => SetProperty(ref _name, value, nameof(Name));
}

这会自动触发 PropertyChanged 事件并通知视图更新。

如果UI界面属性的值是你自身属性名称,那么可以再简化下:

public class NotifyPropertyChangedBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

  public class  ClassA:NotifyPropertyChangedBase
    {
        private int myVar;

        public int MyProperty
        {
            get { return myVar; }
            set
            {
                if (myVar != value)
                {
                    myVar = value;
                    RaisePropertyChanged();//注意这里可以省略属性名称
                }
            }
        }
        
    }

参考

你可能感兴趣的:(wpf,wpf)