Skip to content

Instantly share code, notes, and snippets.

@michaeljbailey
Created April 13, 2015 19:02
Show Gist options
  • Save michaeljbailey/9dc0abebfcb972f64a9c to your computer and use it in GitHub Desktop.
Save michaeljbailey/9dc0abebfcb972f64a9c to your computer and use it in GitHub Desktop.
Wires up the PropertyChanged handler in a type safe and filtered way
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