#121 – Being Notified When the Value of a Dependency Property Changes
November 10, 2010 4 Comments
A class that implements a dependency property can optionally ask to be notified when the value of the property changes. The class specifies a PropertyChangedCallback when registering the property.
PropertyMetadata ageMetadata = new PropertyMetadata( 18, // Default value new PropertyChangedCallback(OnAgeChanged), // ** call when property changes new CoerceValueCallback(OnAgeCoerceValue)); // Register the property AgeProperty = DependencyProperty.Register( "Age", // Property's name typeof(int), // Property's type typeof(Person), // Defining class' type ageMetadata, // Defines default value & callbacks (optional) new ValidateValueCallback(OnAgeValidateValue)); // validation (optional)
The class can use this callback to perform some logic whenever the property value changes, e.g. automatically setting the value of another property.
private static void OnAgeChanged (DependencyObject depObj, DependencyPropertyChangedEventArgs e) { Person p = (Person)depObj; p.AARPCandidate = (int)e.NewValue > 60 ? true : false; }