Return Value

Callbacks based on CoerceValueCallback can be assigned to a dependency property through several different techniques. Each of these techniques requires that you first create a new property metadata object (PropertyMetadata, or a derived class such as FrameworkPropertyMetadata). Create the metadata object using a constructor signature that takes the coerceValueCallback parameter, and assign that parameter to your callback handler. Or construct the metadata by any signature and set the CoerceValueCallback property prior to putting the metadata in use.

One you have this metadata, you can:

Define a new dependency property on a new class, using either signature of Register, giving the metadata as the typeMetadata value.

Implementations of this callback should check the value in baseValue and determine based on either the value or the type whether this is a value that needs to be further coerced.

The CoerceValueCallback for a dependency property is invoked any time that the property system or any other caller calls CoerceValue on a DependencyObject instance, specifying that property's identifier as the dp.

Changes to the property value may have come from any possible participant in the property system. This includes styles, generic invalidation, triggers, propertyvalue inheritance, and local value setting.

Generally you should avoid specifying more than one CoerceValueCallback for any given dependency property (overriding or adding with new metadata for a dependency property that already had a CoerceValueCallback). Only one of the callbacks will be able to act. The acting callback will be the one that was applied to the most derived class in the inheritance as compared to the DependencyObject caller. Other callbacks as assigned to metadata for the dependency property as it existed higher in the owner hierarchy are replaced when the metadata is overridden.

The following example includes an implementation of this callback to coerce the stored value of a dependency property based on other inputs, such as another property's value. In this case, the callback checks to see whether the ShirtType property corresponds to a type of shirt that has buttons; if so it establishes a starting default color for the ButtonColor, if the shirt type has no buttons, it coerces the ButtonColor value back to a starting value, which causes the UI (not shown) to remove that dropdown from the effective choices. For the complete sample, see Custom Classes with Dependency Properties Sample.