Strongly-typed Names for INotifyPropertyChanged

A number of people have asked whether it is possible to implement INotifyPropertyChanged without hard-coding property names as strings inside code.

For example, you would normally write:

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged(new PropertyChangedEventArgs("FirstName"));
    }
}

Unfortunately the default refactoring tools won't search in string literals, so if LastName was renamed to Surname, you'd need to change the string manually.

One option to enforce compile-time detection would be the following:

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged(Property.GetFor( () => this.Name ));
    }
}

It could be implemented quite simply with the following static method:

public class Property
{
    public static PropertyChangedEventArgs GetFor(Expression<Func<object>> propertyNameLambda)
    {
        MemberExpression member = propertyNameLambda.Body as MemberExpression;
        if (member != null)
        {
            return new PropertyChangedEventArgs(member.Member.Name);
        }
        return new PropertyChangedEventArgs("");
    }
}

Personally, I don't mind hard-coding property names too much, but it's hardly a best practices, so you may find the above useful. Just beware that it does come with some overhead at runtime.

c# .net binding lambda
Posted by: Paul Stovell
Last revised: 04 Feb, 2012 05:38 AM History

Trackbacks

Comments

12 Oct, 2009 08:29 AM

Paul,

If the body of the lambda isn't a MemberExpression (in the case of primitive types), you would need to convert it to a UnaryExpression and get the MemberExpression from the Operand.

            var memberExpression = lambda.Body as MemberExpression;
            if (memberExpression == null)
            {
                var unaryExpression = (lambda.Body as UnaryExpression);
                memberExpression = unaryExpression.Operand as MemberExpression;
            }

            return memberExpression.Member.Name;
25 Jul, 2010 05:14 PM

i like men

No new comments are allowed on this post.