2 out of 9 rated this helpful Rate this topic

INotifyPropertyChanged Interface

Updated: July 2010

Notifies clients that a property value has changed.

Namespace:  System.ComponentModel
Assembly:  System (in System.dll)
public interface INotifyPropertyChanged

The INotifyPropertyChanged type exposes the following members.

  Name Description
Public event Supported by the XNA Framework Supported by Portable Class Library PropertyChanged Occurs when a property value changes.
Top

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.

For example, consider a Person object with a property called FirstName. To provide generic property-change notification, the Person type implements the INotifyPropertyChanged interface and raises a PropertyChanged event when FirstName is changed.

For change notification to occur in a binding between a bound client and a data source, your bound type should either:

  • Implement the INotifyPropertyChanged interface (preferred).

  • Provide a change event for each property of the bound type.

Do not do both.

The following code example demonstrates the how to implement the INotifyPropertyChanged interface. When you run this example, you will notice the bound DataGridView control reflects the change in the data source without requiring the binding to be reset.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Drawing;
using System.Data.SqlClient;
using System.Windows.Forms;

// This form demonstrates using a BindingSource to bind
// a list to a DataGridView control. The list does not
// raise change notifications, however the DemoCustomer type 
// in the list does.
public class Form1 : System.Windows.Forms.Form
{
    // This button causes the value of a list element to be changed.
    private Button changeItemBtn = new Button();

    // This DataGridView control displays the contents of the list.
    private DataGridView customersDataGridView = new DataGridView();

    // This BindingSource binds the list to the DataGridView control.
    private BindingSource customersBindingSource = new BindingSource();

    public Form1()
    {
        // Set up the "Change Item" button.
        this.changeItemBtn.Text = "Change Item";
        this.changeItemBtn.Dock = DockStyle.Bottom;
        this.changeItemBtn.Click +=
            new EventHandler(changeItemBtn_Click);
        this.Controls.Add(this.changeItemBtn);

        // Set up the DataGridView.
        customersDataGridView.Dock = DockStyle.Top;
        this.Controls.Add(customersDataGridView);

        this.Size = new Size(800, 200);
        this.Load += new EventHandler(Form1_Load);
    }

    private void Form1_Load(System.Object sender, System.EventArgs e)
    {
        // Create and populate the list of DemoCustomer objects
        // which will supply data to the DataGridView.
        BindingList<DemoCustomer> customerList = new BindingList<DemoCustomer>();
        customerList.Add(DemoCustomer.CreateNewCustomer());
        customerList.Add(DemoCustomer.CreateNewCustomer());
        customerList.Add(DemoCustomer.CreateNewCustomer());

        // Bind the list to the BindingSource.
        this.customersBindingSource.DataSource = customerList;

        // Attach the BindingSource to the DataGridView.
        this.customersDataGridView.DataSource =
            this.customersBindingSource;
    }

    // Change the value of the CompanyName property for the first 
    // item in the list when the "Change Item" button is clicked.
    void changeItemBtn_Click(object sender, EventArgs e)
    {
        // Get a reference to the list from the BindingSource.
        BindingList<DemoCustomer> customerList =
            this.customersBindingSource.DataSource as BindingList<DemoCustomer>;

        // Change the value of the CompanyName property for the 
        // first item in the list.
        customerList[0].CustomerName = "Tailspin Toys";
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }
}

// This is a simple customer class that 
// implements the IPropertyChange interface.
public class DemoCustomer  : INotifyPropertyChanged
{
    // These fields hold the values for the public properties.
    private Guid idValue = Guid.NewGuid();
    private string customerNameValue = String.Empty;
    private string phoneNumberValue = String.Empty;

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    // The constructor is private to enforce the factory pattern.
    private DemoCustomer()
    {
        customerNameValue = "Customer";
        phoneNumberValue = "(555)555-5555";
    }

    // This is the public factory method.
    public static DemoCustomer CreateNewCustomer()
    {
        return new DemoCustomer();
    }

    // This property represents an ID, suitable
    // for use as a primary key in a database.
    public Guid ID
    {
        get
        {
            return this.idValue;
        }
    }

    public string CustomerName
    {
        get
        {
            return this.customerNameValue;
        }

        set
        {
            if (value != this.customerNameValue)
            {
                this.customerNameValue = value;
                NotifyPropertyChanged("CustomerName");
            }
        }
    }

    public string PhoneNumber
    {
        get
        {
            return this.phoneNumberValue;
        }

        set
        {
            if (value != this.phoneNumberValue)
            {
                this.phoneNumberValue = value;
                NotifyPropertyChanged("PhoneNumber");
            }
        }
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Date

History

Reason

July 2010

Removed unneeded reset from binding code example.

Customer feedback.

Did you find this helpful?
(2000 characters remaining)
Community Content Add
Annotations FAQ
The binding is not working if change event type is different from EventHandler.

>For change notification to occur in a binding between a bound client and a data source, your bound type should either:
>Implement the INotifyPropertyChanged interface (preferred).
>Provide a change event for each property of the bound type.
>Do not do both.

Ok, but binding is not working if change event is of a type different from EventHandler. In this case, does not work INotifyPropertyChanged Interface, nor PropertyChanged magic. For example:

    /// <summary>
    /// In this class binding is NOT WORKING.
    /// </summary>
    public class Foo: INotifyPropertyChanged
    {
        string text;

        public string Text
        {
            get { return text; }
            set
            {
                text = value;
                OnTextChanged();
            }
        }

        protected void OnTextChanged()
        {
            if (TextChanged != null)
                TextChanged(this, new MyEventArgs());
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Text"));
        }

        //Here binding is not working, because type is different from EventHandler
        public event EventHandler<MyEventArgs> TextChanged;

        //And here binding is not working too, because declared TextChanged event
        public event PropertyChangedEventHandler PropertyChanged;
    } 

A foundation to build upon
Here's an example implementation that serves as a base class you can build upon. Usage is like this:
public property decimal CurrentBalance {
  get { return this.currentBalance; }
  set {
    if(value != this.currentBalance) {
      this.currentBalance = value;
      OnPropertyChanged(() => CurrentBalance);
    }
  }
}
It adresses the following concerns:
  • Avoids garbage by caching PropertyChangedEventArgs instances. An application has a finite number of properties that report changes, typically in the dozens or hundreds, but do your own profiling to see if the cache is beneficial in your own applications.
  • It supports F2 refactoring by using the now popular lamba expression trick to obtain the property name from code instead of using a string
  • The event is raised in a thread-safe manner
  • Serialization doesn't save event subscribers. Usually, subscribers are GUI controls like DataGrids and TextBoxes, aka things you do not want to serialize. If you do wish to serialize event subscriptions, either modify this implementation or use the OnDeserialized callback (search MSDN for OnDeserializedAttribute) to re-establish the subscription after deserialization.

I hope this can serve as a solid foundation or at least demonstrates some tricks to efficiently deal with property change notifications. I followed established conventions and best practices wherever possible.

/// <summary>Base class for objects that support property change notifications</summary>
[Serializable]
public abstract class Observable : INotifyPropertyChanged {

  /// <summary>Raised when a property of the instance has changed its value</summary>
  [field:NonSerialized]
  public event PropertyChangedEventHandler PropertyChanged;

  /// <summary>Initializes a new trackable object</summary>
  static Observable() {
    eventArgumentCache = new ConcurrentDictionary<string, PropertyChangedEventArgs>();
  }

  /// <summary>Triggers the PropertyChanged event for the specified property</summary>
  /// <param name="propertyName">Name of the property that has changed its value</param>
  /// <remarks>
  ///   This notification should be fired post-change, i.e. when the property has
  ///   already changed its value.
  /// </remarks>
  protected virtual void OnPropertyChanged(string propertyName) {
    enforceChangedPropertyExists(propertyName);

    PropertyChangedEventHandler copy = PropertyChanged;
    if(copy != null) {
      copy(this, getOrCreatePropertyChangedEventArgs(propertyName));
    }
  }

  /// <summary>Triggers the PropertyChanged event for the specified property</summary>
  /// <param name="property">
  ///        Lambda expression for the property that will be reported to have changed
  ///    </param>
  /// <remarks>
  ///   This notification should be fired post-change, i.e. when the property has
  ///   already changed its value.
  /// </remarks>
  protected void OnPropertyChanged<TProperty>(Expression<Func<TProperty>> property) {
    var lambda = (LambdaExpression)property;

    MemberExpression memberExpression;
    {
      var unaryExpression = lambda.Body as UnaryExpression;
      if(unaryExpression != null) {
        memberExpression = (MemberExpression)unaryExpression.Operand;
      } else {
        memberExpression = (MemberExpression)lambda.Body;
      }
    }

    OnPropertyChanged(memberExpression.Member.Name);
  }

  /// <summary>
  ///   Looks up a property changed event argument container for the specified property
  /// </summary>
  /// <param name="propertyName">
  ///   Property whose event argument container will be looked up
  /// </param>
  /// <returns>The event argument container for a property of the specified name</returns>
  private PropertyChangedEventArgs getOrCreatePropertyChangedEventArgs(string propertyName) {
    PropertyChangedEventArgs arguments;
    if(eventArgumentCache.TryGetValue(propertyName, out arguments)) {
      return arguments;
    }

    return eventArgumentCache.GetOrAdd(
      propertyName, new PropertyChangedEventArgs(propertyName)
    );
  }

  /// <summary>Ensures that a property with the specified name exists in the type</summary>
  /// <param name="propertyName">Property name that will be checked</param>
  [Conditional("DEBUG")]
  private void enforceChangedPropertyExists(string propertyName) {
    PropertyInfo property = GetType().GetProperty(propertyName);
    if(property == null) {
      throw new ArgumentException(
        string.Format(
          "Type '{0}' tried to raise a change notifcation for property '{1}', " +
          "but no such property exists!",
          GetType().Name, propertyName
        ),
        "propertyName"
      );
    }
  }

  /// <summary>
  ///   Caches PropertyChangedEventArgs instances to prevent excessive garbage production
  /// </summary>
  private static readonly ConcurrentDictionary<
    string, PropertyChangedEventArgs
  > eventArgumentCache;

}
NotifyPropertyChanged(...) not thread safe
The NotifyPropertyChanged method in the sample is not thread safe.