#121 – Being Notified When the Value of a Dependency Property Changes

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;
        }
Advertisements

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

4 Responses to #121 – Being Notified When the Value of a Dependency Property Changes

  1. Christopher Wodarczyk says:

    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’?

  2. David says:

    Also, you are an AARP candidate at age >= 50 (shudder).

    • Sean says:

      Yes, true. I’m 53, so I know the age at which one starts getting AARP junk mail. I was engaging in wishful thinking.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: