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;

    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.

Drop a brain bomb

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.