#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; }
Is there any reason you couldn’t use p.Age from the depObj instance passed in (since this is the object being modified, I assume…), instead of using the NewValue property on the variable ‘e’?
No, that would work just as well. It seems more natural to me to use the e object to get at the property value.
Also, you are an AARP candidate at age >= 50 (shudder).
Yes, true. I’m 53, so I know the age at which one starts getting AARP junk mail. I was engaging in wishful thinking.