WPF data change notification from custom classes






When binding a WPF control to a custom-made class, changes to property values in the object won’t automatically appear in the control because the control can’t by default recognize changes. The solution is to let the class implement the System.ComponentModel.INotifyPropertyChanged interface. The Interface exposes one event that you execute every time a property changes value. This event is used by the WPF control to know that the value is changed.

First we implement the interface. The function NotifyPropertyChanges is just a help function and not part of the interface. You use it to inside setters later on to minimize code.

public class MyStatistic : INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

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

Then we go on and add the properties we need in the class. Every time the value is changed we execute the event by calling the NotifyPropertyChanged method as shown in the example below. The string we send as a parameter is the name of the specific property that has been updated.

private Int32 mStatCrossUpdated = 0;
public Int32 StatCrossUpdated
{
  get
  {
    return mStatCrossUpdated;
  }
  private set
  {
    if (mStatCrossUpdated != value)
    {
      mStatCrossUpdated = value;
      NotifyPropertyChanged("StatCrossUpdated");
    }
  }
}






Some important things to remember are:

  • Always update the value by referring to processed and never mProcessed. If you update mProcessed then the event is never executed.
  • Include a check to see if the new value is different from the old value. Otherwise you’ll get a lot of extra overhead processing to update the UI even though there is no new data to update with.
  • The binding must of course be set to a Mode that supports updates later on – OneWay or TwoWay. By not setting Mode is usually working well.