Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Notify Clients when Changes Happen

Scenario/Problem:

You want users of your class to know when data inside the class changes.

Solution:

Implement the INotifyPropertyChanged interface (located in System.ComponentModel).

using System.ComponentModel;
...
class MyDataClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

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

    private int _tag = 0;
    public int Tag
    {
        get
        { return _tag; }
        set
        {
            _tag = value;
            OnPropertyChanged("Tag");
        }
    }
}

The Windows Presentation Foundation (WPF) makes extensive use of this interface for data binding, but you can use it for your own purposes as well.

To consume such a class, use code similar to this:

void WatchObject(object obj)
{
    INotifyPropertyChanged watchableObj = obj as INotifyPropertyChanged;
    if (watchableObj != null)
    {
        watchableObj.PropertyChanged += new
                PropertyChangedEventHandler(data_PropertyChanged);
    }
}

void data_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    //do something when data changes
}
  • + Share This
  • 🔖 Save To Your Account