Como: Override Metadata for a Dependency Property
This example shows how to override default dependency property metadata that comes from an inherited class, by calling the OverrideMetadata method and providing type-specific metadata.
Exemplo
By defining its PropertyMetadata, a class can define the dependency property's behaviors, such as its default value and property system callbacks. Many dependency property classes already have default metadata established as part of their registration process. This includes the dependency properties that are part of the WPF API. A class that inherits the dependency property through its class inheritance can override the original metadata so that the characteristics of the property that can be altered through metadata will match any subclass-specific requirements.
Overriding metadata on a dependency property must be done prior to that property being placed in use by the property system (this equates to the time that specific instances of objects that register the property are instantiated). Calls to OverrideMetadata must be performed within the static constructors of the type that provides itself as the forType parameter of OverrideMetadata. If you attempt to change metadata once instances of the owner type exist, this will not raise exceptions, but will result in inconsistent behaviors in the property system. Also, metadata can only be overridden once per type. Subsequent attempts to override metadata on the same type will raise an exception.
In the following example, the custom class MyAdvancedStateControl overrides the metadata provided for StateProperty by MyAdvancedStateControl with new property metadata. For instance, the default value of the StateProperty is now true when the property is queried on a newly constructed MyAdvancedStateControl instance.
public class MyStateControl : ButtonBase
{
public MyStateControl() : base() { }
public Boolean State
{
get { return (Boolean)this.GetValue(StateProperty); }
set { this.SetValue(StateProperty, value); }
}
public static readonly DependencyProperty StateProperty = DependencyProperty.Register(
"State", typeof(Boolean), typeof(MyStateControl),new PropertyMetadata(false));
}
...
public class MyAdvancedStateControl : MyStateControl
{
public MyAdvancedStateControl() : base() { }
static MyAdvancedStateControl()
{
MyStateControl.StateProperty.OverrideMetadata(typeof(MyAdvancedStateControl), new PropertyMetadata(true));
}
}
Consulte também
Conceitos
Visão geral sobre propriedades de dependência
Propriedades de Dependência Personalizada