Click here to Skip to main content
15,881,812 members
Articles / Desktop Programming / WPF
Tip/Trick

Make OnPropertyChanged events safe for refactoring

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
4 Oct 2011CPOL 32.2K   8   2
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
I’m a Software Engineer at Microsoft working on the Azure Portal. Before that I spent about 20 years developed various business applications at a number of different companies. I have a passion for writing clean, scalable code and sharing what I’ve learned with others.

I also help run the Casco Bay .Net User Group

Comments and Discussions

 
QuestionNice code but there is a potential performance hit Pin
SBendBuckeye14-Feb-13 8:05
SBendBuckeye14-Feb-13 8:05 
MVVM – Lambda vs INotifyPropertyChanged vs DependencyObject
http://blog.quantumbitdesigns.com/2010/01/26/mvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject/[^]
Have a great day!

j2associates_NO_SPAM_@yahoo.com

QuestionNice Pin
Eaverae3-Oct-11 20:46
Eaverae3-Oct-11 20:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.