Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Make OnPropertyChanged events safe for refactoring

0.00/5 (No votes)
4 Oct 2011 1  
Use OnPropertyChanged events without Magic Strings
Here's a little trick I picked up somewhere that allows you to pass the actual property rather than the property name when raising an OnPropertyChanged event. It allows for safe refactoring of property names as well as compile time validation.

With this code, instead of this:
OnPropertyChanged("PropertyName")

you can use this:
OnPropertyChanged(() => this.PropertyName)


C#
public event PropertyChangedEventHandler PropertyChanged;
 
//Traditional OnPropertyChanded method
public void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
 
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
 
//New and improved OnPropertyChanged method
protected void OnPropertyChanged<t>(Expression<func><t>> expression)
{
    OnPropertyChanged(GetProperty(expression).Name);
}
 
//Helper method
public static PropertyInfo GetProperty<t>(Expression<func><t>> expression)
{
    PropertyInfo property = GetMember(expression) as PropertyInfo;
    if (property == null)
    {
        throw new ArgumentException("Not a property expression", GetMember(() => expression).Name);
    }
 
    return property;
}
        
//Helper method
public static MemberInfo GetMember<t>(Expression<func><t>> expression)
{
    if (expression == null)
    {
        throw new ArgumentNullException(GetMember(() => expression).Name);
    }

    return GetMemberInfo(expression as LambdaExpression);
}
        
//Helper method
public static MemberInfo GetMemberInfo(LambdaExpression lambda)
{
    if (lambda == null)
    {
        throw new ArgumentNullException(GetMember(() => lambda).Name);
    }

    MemberExpression memberExpression = null;
    if (lambda.Body.NodeType == ExpressionType.Convert)
    {
        memberExpression = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
    }
    else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
    {
        memberExpression = lambda.Body as MemberExpression;
    }
    else if (lambda.Body.NodeType == ExpressionType.Call)
    {
        return ((MethodCallExpression)lambda.Body).Method;
    }

    if (memberExpression == null)
    {
        throw new ArgumentException("Not a member access", GetMember(() => lambda).Name);
    }

    return memberExpression.Member;
}
</t></func></t></t></func></t></t></func></t>


10/4/11 - Added a needed method to the sample code and fixed a few areas where the parameter definition got munched.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here