#164 – Overriding Metadata for an Inherited Dependency Property
December 23, 2010 3 Comments
When deriving a new child class, you inherit the parent’s dependency properties. You might also want to change the behavior of one or more of the dependency properties. You can do this to some extent by overriding the metadata for a dependency property.
Overriding the metadata in the child class doesn’t change the behavior of the dependency property in the parent class.
In the example below, we create a new class and override metadata for several properties, changing the default values.
public class ThermometerSlider : Slider { static ThermometerSlider() { // Defaults for standard Slider: Min = 0, Max = 10, Value = 0 // Defaults for ThermometerSlider: Min = -40, Max = 120, Value = 70 // Change default Minimum to -40.0 MinimumProperty.OverrideMetadata(typeof(ThermometerSlider), new FrameworkPropertyMetadata(-40.0)); // Change default Maximum to 120 MaximumProperty.OverrideMetadata(typeof(ThermometerSlider), new FrameworkPropertyMetadata(120.0)); // Change default Value to 70 ValueProperty.OverrideMetadata(typeof(ThermometerSlider), new FrameworkPropertyMetadata(70.0)); } }
The metadata type must match the type in the original property (e.g. FrameworkPropertyMetadata, UIPropertyMetadata, or PropertyMetadata).
Pingback: #165 – Overriding Metadata Can Result in Merged Metadata « 2,000 Things You Should Know About WPF
Having a subclass of lets say DataGrid with the following call in the static constructor:
ItemsSourceProperty.OverrideMetadata(typeof(ChildDataGrid), new FrameworkPropertyMetadata((PropertyChangedCallback)null, OnCoerceItemSoureProperty));
Causes both the DataGrid and the Subclass OnCoerceItemSourceProperty callbacks to fire.
So like the comment before me, I don’t think its fair to say overriding metadata “CoerceValueCallback replaces the existing one” because the parents callback is unfazed.
It should get replaced. That’s the behavior that I see and what is documented in http://msdn.microsoft.com/en-us/library/ms752375.aspx (look for “CoerceValueCallback” implementations are replaced).
Have you tried setting up your coerce value callback to have a new/unique name, to double-check that the parent’s callback is still getting called? How are you verifying that it’s getting called–setting a breakpoint in DataGrid?