How to: Override Metadata for a Dependency Property

In this article

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.

Example

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
Inherits ButtonBase
Public Sub New()
MyBase.New()
End Sub
Public Property State() As Boolean
Get
Return CType(Me.GetValue(StateProperty), Boolean)
End Get
Set(ByVal value As Boolean)
Me.SetValue(StateProperty, value)
End Set
End Property
Public Shared ReadOnly StateProperty As DependencyProperty = DependencyProperty.Register("State", GetType(Boolean), GetType(MyStateControl),New PropertyMetadata(False))
End Class

See Also

The feedback system for this content will be changing soon. Old comments will not be carried over. If content within a comment thread is important to you, please save a copy. For more information on the upcoming change, we invite you to read our blog post.