• Net3.5及以上版本INotifyPropertyChanged接口的友好用法


    1、核心类BaseNotifyPropertyChanged ,主要用来封装NotifyProperty的执行方法

    View Code
     1     public abstract class BaseNotifyPropertyChanged : INotifyPropertyChanged
     2     {
     3         public event PropertyChangedEventHandler PropertyChanged;
     4 
     5         protected void RaisePropertyChanged<T>(
     6             Expression<Func<T>> propertyExpresssion)
     7         {
     8             if (propertyExpresssion == null)
     9             {
    10                 throw new ArgumentNullException("propertyExpression");
    11             }
    12 
    13             var memberExpression = propertyExpresssion.Body as MemberExpression;
    14             if (memberExpression == null)
    15             {
    16                 throw new ArgumentException("PropertySupport_NotMemberAccessExpression_Exception""propertyExpression");
    17             }
    18 
    19             var property = memberExpression.Member as PropertyInfo;
    20             if (property == null)
    21             {
    22                 throw new ArgumentException("PropertySupport_ExpressionNotProperty_Exception""propertyExpression");
    23             }
    24 
    25             string propertyName = property.Name;
    26             object propertyValue = property.GetValue(thisnull);
    27 
    28             var getMethod = property.GetGetMethod(true);
    29             if (getMethod.IsStatic)
    30             {
    31                 throw new ArgumentException("PropertySupport_StaticExpression_Exception""propertyExpression");
    32             }
    33             this.RaisePropertyChanged(propertyName);
    34         }
    35 
    36         private void RaisePropertyChanged(string propertyName)
    37         {
    38             if (PropertyChanged != null)
    39                 PropertyChanged(thisnew PropertyChangedEventArgs(propertyName));
    40         }
    41     }

         说明:abstract 是为了其他人不能直接初始化该类。

    2、Example

    View Code
     1     public class User : BaseNotifyPropertyChanged
     2     {
     3         private string name;
     4         public string Name
     5         {
     6             get { return name; }
     7             set
     8             {
     9                 name = value;
    10                 RaisePropertyChanged(() => this.Name);
    11             }
    12         }
    13     }

     So is easy

  • 相关阅读:
    练习题
    java关键字
    循环结构
    第一天的学习
    爬虫的简单介绍
    Windows10 专业版秘钥激活
    flask补充
    Flask框架
    小程序登录、授权、支付
    赃读、不可重复读 和 幻读
  • 原文地址:https://www.cnblogs.com/maozhh/p/2417568.html
Copyright © 2020-2023  润新知