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

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

csharp 复制代码
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 方法来设置属性,如下所示:

csharp 复制代码
private string _name;
public string Name
{
    get => _name;
    set => SetProperty(ref _name, value, nameof(Name));
}

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

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

csharp 复制代码
public class NotifyPropertyChangedBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
csharp 复制代码
  public class  ClassA:NotifyPropertyChangedBase
    {
        private int myVar;

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

参考

相关推荐
武藤一雄5 小时前
WPF Command 设计思想与实现剖析
windows·微软·c#·.net·wpf·.netcore
Aevget5 小时前
DevExpress WPF中文教程:Data Grid - 服务器模式和即时反馈模式
.net·wpf·界面控件·devexpress·ui开发
武藤一雄5 小时前
WPF 资源解析:StaticResource & DynamicResource 实战指南
微软·c#·.net·wpf·.netcore
c#上位机5 小时前
wpf路径
wpf
武藤一雄5 小时前
WPF UI 开发深度指南:资源 (Resources)、样式 (Style) 与触发器 (Trigger) 全解析
ui·c#·.net·wpf·.netcore·avalonia
Poetinthedusk1 天前
WPF获得当前电脑的储存和运存
wpf
unicrom_深圳市由你创科技1 天前
Qt、MFC、WinForm、WPF,哪个做上位机界面更好?
qt·wpf·mfc
暮雪倾风2 天前
【WPF】使用Costura.Fody将工程打包为单个EXE文件
wpf·exe·windows原生开发
咖啡の猫2 天前
Jedis快速入门
wpf
Scout-leaf2 天前
WPF新手村教程(五)— 附魔教学(绑定)
c#·wpf