WPF INotifyPropertyChanged
首先感叹一下,INotifyPropertyChanged这个单词有点长,我现在都还记不住……
其次再感叹一下,实现这个接口,属性的封装还是有点麻烦啊。
属性什么的我就喜欢 xxx{get;set;}……不得不说我是一个很懒的猿~
首先来看看一般的实现方式:
public class NotificationObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// 实现依赖属性 /// </summary> /// <param name="propertyName"></param> public void RaisePropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private string _userName; //private const string UserNameProperty="UserName"; public string UserName { get { return _userName; } set { _userName= value; this.RaisePropertyChanged("UserName");//这样的写法是不是很不爽? 或者this.RaisePropertyChanged(UserNameProperty) } } }
对于以上的写法,实在有点不爽,不写const字段吧,比较容易填错,写了吧,哎呀好费事儿啊。
很幸运的是不仅是我觉得麻烦,有大神已经给出了解决之道:(很抱歉,忘记是哪位大神的文章了,刚刚翻了一下没找到,这里就直接上代码了)
public static class NotificationObjectEx { /// <summary> /// 使用:RaisePropertyChanged(vm=>vm.属性) /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="propertyChangedBase"></param> /// <param name="expression"></param> public static void RaisePropertyChanged<T, TProperty>(this T propertyChangedBase, Expression<Func<T, TProperty>> expression) where T : NotificationObject { var memberExpression = expression.Body as MemberExpression; if (memberExpression != null) { string propertyName = memberExpression.Member.Name; propertyChangedBase.RaisePropertyChanged(propertyName); } else throw new NotImplementedException(); } }
于是就可以这样:this.RaisePropertyChanged(vm=>vm.UserName); 是不是觉得爽多了?麻麻再也不用担心哦拼错属性名称了~
最后,好记性不如烂笔头~~INotifyPropertyChanged、INotifyPropertyChanged、INotifyPropertyChanged、INotifyPropertyChanged、INotifyPropertyChanged……