Skip to content

Instantly share code, notes, and snippets.

@geirsagberg
Created July 16, 2013 10:39
Show Gist options
  • Save geirsagberg/6007642 to your computer and use it in GitHub Desktop.
Save geirsagberg/6007642 to your computer and use it in GitHub Desktop.
Handy methods for property reflection, and subscription to properties in MVVM
/// <summary>
/// Methods for handling property names and values, using reflection.
/// </summary>
public static class PropertyUtil
{
public static string GetPropertyName<TObject, TValue>(this TObject type,
Expression<Func<TObject, TValue>> propertySelector)
{
return GetPropertyNameCore(propertySelector.Body);
}
public static string GetPropertyName<TObject, TValue>(Expression<Func<TObject, TValue>> propertySelector)
{
return GetPropertyNameCore(propertySelector.Body);
}
private static string GetPropertyNameCore(Expression propertySelector)
{
if (propertySelector == null)
throw new ArgumentNullException("propertySelector", "propertyRefExpr is null.");
MemberExpression memberExpr = propertySelector as MemberExpression;
if (memberExpr == null)
{
UnaryExpression unaryExpr = propertySelector as UnaryExpression;
if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Convert)
memberExpr = unaryExpr.Operand as MemberExpression;
}
if (memberExpr != null && memberExpr.Member.MemberType == MemberTypes.Property)
return memberExpr.Member.Name;
throw new ArgumentException("No property reference expression was found.",
"propertySelector");
}
public static void SetValueForProperty<TObject, TValue>(this TObject type, Expression<Func<TObject, TValue>> propertySelector, TValue value)
{
string propertyName = type.GetPropertyName(propertySelector);
var property = type.GetType().GetProperty(propertyName);
property.SetValue(type, value, null);
}
public static object GetValueForProperty<TObject, TValue>(this TObject type, Expression<Func<TObject, TValue>> propertySelector)
{
string propertyName = type.GetPropertyName(propertySelector);
var property = type.GetType().GetProperty(propertyName);
return property.GetValue(type, null);
}
public static void SubscribeToProperty<T>(this T me, Expression<Func<T, object>> propertySelector, Action<T> callback) where T : INotifyPropertyChanged
{
var propertyName = GetPropertyName(propertySelector);
me.PropertyChanged += (sender, args) =>
{
if (args.PropertyName == propertyName)
{
callback(me);
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment