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

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

ExpandedBlockStart.gif 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

ExpandedBlockStart.gif 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

转载于:https://www.cnblogs.com/maozhh/archive/2012/03/26/2417568.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值