Tuesday, March 15, 2011

A strongly typed implementation of INotifyPropertyChanged

INotifyPropertyChanged is an interface used to notify clients that a property has changed. It's used heavily in Silverlight and WPF in combination with databinding and when used it makes updating the ui and then retrieving data from the ui very simple.

I have a major gripe with the way it's generally done though. There are usually two places where the parameter name is specified as text. In the xaml code:
<TextBlock Text="{Binding Name}" />

and in the viewmodel
public class Person : INotifyPropertyChanged
{
  public string Name
  {
    get { return _name; }
    set { _name = value; NotifyPropertyChanged("Name"); }
  }
}

The main problem here is that if you refactor or rename a property you might miss these two locations and will not be alerted. Your app will not work and unless you're testing all your ui field databindings you'll never notice.

Unfortunately we can't fix this problem in the xaml, but in the viewmodel here is a neat typesafe implmentation of NotifyPropertyChanged.

protected void NotifyPropertyChanged<T>(Expression<Func<T>> expression)
 {
   if (PropertyChanged != null)
   {
     PropertyChanged(this, new PropertyChangedEventArgs(expression.MemberName()));
   }
}

public event PropertyChangedEventHandler PropertyChanged;

Usage:
public class Person : INotifyPropertyChanged
{
  public string Name
  {
      get { return _name; }
      set { _name = value; NotifyPropertyChanged(() => Name); }
  }
}

No comments: