现在的位置: 首页 > 综合 > 正文

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

2013年02月25日 ⁄ 综合 ⁄ 共 2086字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.