INotifyPropertyChanged with lambdas

There are several ways of implementing INotifyPropertyChanged in WPF applications.

One that I particularly like is by using PostSharp to implement INotifyPropertyChanged.

If you are not comfortable with PostSharp you can at least get rid of those nasty strings in standard implementation:

public class Model : ViewModeBase
{
    private string _status;
    public string Status
    {
        get { return _status; }
        set
        {
            _status = value;
            OnPropertyChanged("Status");
        }
    }
};

Labda expressions look nicer and are easier to refactor:

public class MyModel : ViewModeBase
{
    private string _status;
    public string Status
    {
        get { return _status; }
        set
        {
            _status = value;
            OnPropertyChanged(() => Status);
        }
    }
};

First thing we need to do is to create base class for all our ViewModels:

public class ViewModelBase
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    protected void OnPropertyChanged(
        Expression<func<object>> expression)
    {
        string propertyName = PropertyName.For(expression);
        this.PropertyChanged(
            this,
            new PropertyChangedEventArgs(propertyName));
    }
};

The implementation of PropertyName.For is very straightforward: How to get property name from lambda.

That’s it!
Nice, easy to refactor, compile-time checked INotifyPropertyChanged implementation.

Tags:  

Questions?

Consider using our Q&A forum for asking any questions.

2 Responses to “INotifyPropertyChanged with lambdas”

  1. Mark Seemann Says:

    …and now we are at it, here’s how to unit test those events using a fluent interface with lambda: http://blog.ploeh.dk/2009/08/06/AFluentInterfaceForTestingINotifyPropertyChanged.aspx

  2. INotifyPropertyChanged with custom targets Says:

    […] You can use PostSharp for that, you should at least use lambda expressions instead of strings. […]