Created
April 13, 2015 19:02
-
-
Save michaeljbailey/9dc0abebfcb972f64a9c to your computer and use it in GitHub Desktop.
Wires up the PropertyChanged handler in a type safe and filtered way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class NotifyPropertyChangedExtensions | |
{ | |
private static PropertyInfo GetPropertyInfo<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyExpression) | |
{ | |
var type = typeof(TSource); | |
var memberExpression = propertyExpression.Body as MemberExpression; | |
if (memberExpression == null) | |
{ | |
var message = string.Format("Expression '{0}' refers to a method, not a property.", propertyExpression); | |
throw new ArgumentException(message); | |
} | |
var propertyInfo = memberExpression.Member as PropertyInfo; | |
if (propertyInfo == null) | |
{ | |
var message = string.Format("Expression '{0}' refers to a field, not a property.", propertyExpression); | |
throw new ArgumentException(message); | |
} | |
if (propertyInfo.ReflectedType == null || (type != propertyInfo.ReflectedType && !type.IsSubclassOf(propertyInfo.ReflectedType))) | |
{ | |
var message = string.Format("Expresion '{0}' refers to a property that is not from type {1}.", propertyExpression, type); | |
throw new ArgumentException(message); | |
} | |
return propertyInfo; | |
} | |
public static void RegisterChangeHandler<TViewModel, TProperty>(this TViewModel target, Expression<Func<TViewModel, TProperty>> propertyExression, Action<TViewModel, PropertyChangedEventArgs> handler) where TViewModel : INotifyPropertyChanged | |
{ | |
var propertyName = GetPropertyInfo(propertyExression).Name; | |
target.PropertyChanged += (sender, args) => | |
{ | |
if (args.PropertyName != propertyName) | |
{ | |
return; | |
} | |
handler.Invoke(target, args); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment