INotifyPropertyChanged:html
该接口包含一个事件, 针对属性发生变动时, 执行该事件发生。函数
// // 摘要: // 通知客户端属性值已更改。 public interface INotifyPropertyChanged { // // 摘要: // 在属性值更改时发生。 event PropertyChangedEventHandler PropertyChanged; }
接下来, 用一个简单的示例说明其简单使用方法(大部分经常使用的作法演示):this
1.定义一个ViewModelBase 继承INotifyPropertyChanged 接口, 添加一个虚函数用于继承子类的属性进行更改通知spa
2.MainViewModel中两个属性, Code,Name 进行了Set更改时候的调用通知,code
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的时候, 都须要传一个本身的属性名, 这样不少余htm
改造:blog
CallerMemberName继承
该类继承与 Attribute, 不难看出, 该类属于定义在方法和属性上的一种特效类, 实现该特性容许获取方法调用方的方法或属性名称接口
// // 摘要: // 容许获取方法调用方的方法或属性名称。 [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class CallerMemberNameAttribute : Attribute { // // 摘要: // 初始化 System.Runtime.CompilerServices.CallerMemberNameAttribute 类的新实例。 public CallerMemberNameAttribute(); }