ObservableObject for WPF MVVM

For those of you who know what INotifyPropertyChanged is and also know what kind of a maintenance burden the OnPropertyChanged(“Property”) calls are I would like to share my favorite implementation of the ObservableObject.

public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void SetAndNotify<T>(ref T field, T value, Expression<Func<T>> property)
    {
        if (!object.ReferenceEquals(field, value))
        {
            field = value;
            this.OnPropertyChanged(property);
        }
    }

    protected virtual void OnPropertyChanged<T>(Expression<Func<T>> changedProperty)
    {
        if (PropertyChanged != null)
        {
            string name = ((MemberExpression)changedProperty.Body).Member.Name;
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

Instead of using strings for property change notifications you use lambda expressions. This is beneficial because refactoring tools will pick this up instead of having to manually change the magic strings. It also will give you compile time errors if you have gotten something wrong. It also lets you maintain 1 statement setters in properties instead of multiple statements. Using the ObservableObject looks something like this:

public class Customer : ObservableObject
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.SetAndNotify(ref this.name, value, () => this.Name); }
    }
}

Simple and effective.

Author: justinmchase

I'm a Software Developer from Minnesota.

Leave a Reply

Discover more from justinmchase

Subscribe now to keep reading and get access to the full archive.

Continue reading