#792 – Being Notified When an Object’s Properties Change, Part I
March 4, 2013 3 Comments
If you write a class, there’s a pattern that you can implement, to let users of your class know when a property value changes. This pattern is implemented by implementing the INotifyPropertyChanged in your class.
The purpose of this pattern is to let client code know that some property value has changed, in situations where that code didn’t initiate the change. For example, this pattern is used in data binding.
Below is an example of a class that implements INotifyPropertyChanged. The class defines an event that is fired whenever any property value changes.
public class Dog : INotifyPropertyChanged { private string name; public string Name { get { return name; } set { if (name != value) { name = value; RaisePropertyChanged("Name"); } } } private int age; public int Age { get { return age; } set { if (age != value) { age = value; RaisePropertyChanged("Age"); } } } public Dog(string name, int age) { Name = name; Age = age; } public void AgeThisDog() { Age++; } //-- INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string prop) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } }
Part II of this topic will show how client code can use this new event.