Business objects and controls do not have a generic way to
provide notification when a property changes. The current convention is to
provide a property changed event for each property (e.g. "PropertyName"Changed
event handler). For business object types or controls with many properties,
this can lead to a cumbersome object model. INotifyPropertyChanged provides a
simpler, interface based approach to providing property change notification.
Sample: Simple Binding with
INotifyPropertyChanged Change Notification (VS 2005) (VS Project:
PropertyChangeNotification)
using System.ComponentModel;
public class CurrentTime : INotifyPropertyChanged
{
System.Windows.Forms.Timer _timer;
public CurrentTime()
{
/***************************************************************
* Use a timer to keep track of the current time
***************************************************************/
_timer = new System.Windows.Forms.Timer();
/***************************************************************
* Update the time every second
***************************************************************/
_timer.Interval = 1000;
_timer.Tick += delegate { this.Now = DateTime.Now; };
_timer.Start();
}
/*******************************************************************
* Use a timer to keep track of the current time
*******************************************************************/
private DateTime _now = DateTime.Now;
/*******************************************************************
* Property Change Notification fired – bound UI elements will
* update when this property changed
*
* This uses INotifyPropertyChanged
*******************************************************************/
public DateTime Now
{
get { return _now; }
private set
{
if (_now != value)
{
_now = value;
OnPropertyChanged("Now");
}
}
}
/*******************************************************************
* Provide the INotifyPropertyChanged.PropertyChanged event
*******************************************************************/
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (null != PropertyChanged)
{
PropertyChanged(this, e);
}
}
}