Implement the INotifyPropertyChanged interface (located in
Code:
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:
Code:
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
}