INotifyPropertyChanged PropertyChangedEventArgs获取变更属性

INotifyPropertyChanged:

该接口包含一个事件, 针对属性发生变更时, 执行该事件发生。

    //
    // 摘要:
    //  通知客户端属性值已更改。
    public interface INotifyPropertyChanged
    {
        //
        // 摘要:
        //     在属性值更改时发生。
        event PropertyChangedEventHandler PropertyChanged;
    }

接下来, 用一个简单的示例说明其简单使用方法(大部分常用的做法演示):

1.定义一个ViewModelBase 继承INotifyPropertyChanged 接口, 添加一个虚函数用于继承子类的属性进行更改通知

2.MainViewModel中两个属性, Code,Name 进行了Set更改时候的调用通知,

public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }


    public class MainViewModel : ViewModelBase
    {
        private string name;
        private string code;

        public string Name
        {
            get { return name; }
            set { name = value; OnPropertyChanged("Name"); }
        }

        public string Code
        {
            get { return code; }
            set { code = value; OnPropertyChanged("Code"); }
        }
    }

每个属性调用OnPropertyChanged的时候, 都需要传一个自己的属性名, 这样很多余

改造:

CallerMemberName

 该类继承与 Attribute, 不难看出, 该类属于定义在方法和属性上的一种特效类, 实现该特性允许获取方法调用方的方法或属性名称

//
    // 摘要:
    //     允许获取方法调用方的方法或属性名称。
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public sealed class CallerMemberNameAttribute : Attribute
    {
        //
        // 摘要:
        //     初始化 System.Runtime.CompilerServices.CallerMemberNameAttribute 类的新实例。
        public CallerMemberNameAttribute();
    }

源文:https://www.cnblogs.com/zh7791/p/9933954.html

原文地址:https://www.cnblogs.com/shy1766IT/p/11305412.html