软件编程
位置:首页>> 软件编程>> C#编程>> C#接口INotifyPropertyChanged使用方法

C#接口INotifyPropertyChanged使用方法

作者:痕迹g  发布时间:2021-11-22 13:33:53 

标签:C#,INotifyPropertyChanged,接口,用法

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的时候, 都需要传一个自己的属性名, 这样是不是很多余?对, 很多余。

改造

看到有些文章给基类的参数修改为表达式树, 这样实现的时候,传递一个Lambda表达式, 我觉得这是不治标不治本吗?如下:

C#接口INotifyPropertyChanged使用方法

说明: 原来直接传递一个固定的string类型实参, 不说换成lambda的性能问题, 同样带来的问题你还是固定的需要去书写这个参数。 不建议这么做!

CallerMemberName

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

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

改造ViewModelBase:

C#接口INotifyPropertyChanged使用方法

改造之后, 是不是发现明显区别:

不用传递参数, 不用书写lambda表达式, 也不用担心其传递的参数安全, 直接根据读取属性名!

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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com