Implement and consume change notification properties

May include but is not limited to: implementing INotifyPropertyChanged, using INotifyCollectionChanged(ObservableCollection)

We’ve discussed that WPF has some nice data-binding support which lets us implement two-way bindings. But it won’t work from itself, especially not for you domain classes. If you’d like to receive change notification support, then you need an interface what will do just that for you. It’s called INotifyPropertyChanged, and exposes one event, with the following signature:

public event PropertyChangedEventHandler PropertyChanged;

It’s up to you to fire this event whenever one of your properties changes. A decent example:

private int id;
public int ID
get { return id; }
set { id = value; OnPropertyChanged(new PropertyChangedEventArgs(“ID”)); }

Nice and simple, isn’t it? Of course OnPropertyChanged is a method handler waiting for you to be written. What should be in it? Well, nothing really. You just need to raise the PropertyChangedEvent with the supplied EventArgs object. OK, here’s an example:

public void OnPropertyChanged(PropertyChangedEventArgs e)
  if(PropertyChanged != null)
    PropertyChanged(this, e);

You might wonder that what happens when you pass in an empty string. Well, in that case every property would be reevaluated. You might also wonder that what is the whole point of this, because domain classes won’t change just when you change them in the UI. To borrow an example from Pro WPF in C# 2010, it’s easily imaginable that you have a button, which increments the tax rate of a price – in code. Then you would have no way to get the new tax rate, wouldn’t you?

There’s another interface for notification – but this time, on collections. It’s called INotifyCollectionChanged, and exposes one event, too. You’d work with it the exact same way as with INotifyPropertyChanged. But fortunately, WPF comes with a collection of type ObservableCollection<T> which implements this interface for you. All you have to do is use this class (instead of IEnumerable<T>) and you get change notification support for all your data wrapped inside it.


Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: