An easier way to manage INotifyPropertyChanged

time to read 2 min | 307 words

If you are working with WPF or Silverlight view models, then you know that one of the more annoying things to deal with is implementing INotifyPropertyChanged to support refreshing the UI when the model is changed.

At some point, I got tried of that and wrote this:

public class Observable<T> : INotifyPropertyChanged
{
	private T value;

	public Observable()
	{
		
	}

	public Observable(T value)
	{
		this.value = value;
	}

	public T Value
	{
		get{ return value;}
		set
		{
			this.value = value;
			PropertyChanged(this, new PropertyChangedEventArgs("Value"));
		}
	}

	public static implicit operator T(Observable<T> val)
	{
		return val.value;
	}


	public event PropertyChangedEventHandler PropertyChanged = delegate { };
}

This doesn’t seem to be very interesting, right? But it has some nice properties. Here is an example of a view model making use of this.

public class Model : IPagingInformation
{
	public Observable<bool> AllowEditing { get; set; }

	public Observable<int> NumberOfPages { get; set; }

	public Observable<int> CurrentPage { get; set; }
}

One of the nice things about the Observable class is that it is make it easy to work with the stored values. For example:

Model.AllowEditing.Value = !Model.AllowEditing;
Model.CurrentPage.Value = Model.CurrentPage +1;

In other words, you can treat the object as if it wasn’t a wrapper for reading purposes. I could make it both ways, but then I would have no way of maintaining the same instance for updates. Overall, I found the it made it quite a bit easier to deal with the task of UI updates.