INotifyPropertyChanged with lambdas
Tuesday, February 16th, 2010There 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, compilaile-time checked INotifyPropertyChanged implementation.
