#793 – Being Notified When an Object’s Properties Change, Part II

Once you’ve implemented the INotifyPropertyChanged interface in a class, you can subscribe to the PropertyChanged event for an instance of your class.  Assuming that you’ve implemented INotifyPropertyChanged properly, the event will fire whenever any property value in the object changes.

The code below assumes that the Dog class implements INotifyPropertyChanged.

        static void Main(string[] args)
        {
            Dog d = new Dog("Bob", 5);

            d.PropertyChanged += d_PropertyChanged;

            d.Name = "Bob Jr.";
            d.AgeThisDog();
            d.Age = 10;
        }

        static void d_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            Console.WriteLine(string.Format("Property {0} just changed", e.PropertyName));
        }

793-001

The PropertyChanged event handler receives an instance of a PropertyChangedEventArgs object, which just contains a PropertyName property that tells you which property changed.  It pass any information about either the old or the new values of the property.  The assumption is that client code can read the updated property value on their own.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #793 – Being Notified When an Object’s Properties Change, Part II

  1. Pingback: Dew Drop – March 5, 2013 (#1,509) | Alvin Ashcraft's Morning Dew

  2. Pingback: The Daily Six Pack: March 11, 2013 | Dirk Strauss

Leave a comment