A while a go, I had a post regarding how to implement the INotifyPropertyChanged event in a more proper fashion. You didn’t have to hard-code the property name, and could instead use a linq expression, which with a help of an extension method, the name of the property is easily extracted, and passed to raise the PropertyChanged event. Simple, right?
publicstaticclassEventExtension { publicstaticvoidNotify<T, TValue>(this T instance, PropertyChangedEventHandler handler, Expression<Func<T, TValue>> selector) where T : INotifyPropertyChanged { if (handler != null) { var memberExpression = selector.Body as MemberExpression; if (memberExpression == null) thrownew InvalidOperationException(“selector should be a MemberExpression.”);
handler(instance, new PropertyChangedEventArgs(memberExpression.Member.Name)); } } }
publicstring Name { get { return _Name; } set { _Name = value; this.Notify(base.PropertyChanged, o => o.Name); } } }
Should work like a charm, right? WRONG! you’ll end up with a compile time error. It is like the extension method does not like my inherited PropertyChanged event. The drawback to the latter method was that you could not use it in inheritance context.
I need to implement INotifyPropertyChanged only once (Layer Supertype, anyone?). I had to come up with something to be able to work in inheritance context. Finally, here’s it :