FREE BOOK

Chapter 2: Creating Versatile Types

Posted by SAMS Publishing Free Book | C# Language March 24, 2010
Tags: C#
This chapter is all about making your own objects as useful and versatile as possible. In many cases, this means implementing the standard interfaces that .NET provides or simply overriding base class methods.

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

}

Total Pages : 12 7891011

comments