Edit

Share via


How to implement a dependency property (WPF .NET)

This article describes how to implement a dependency property by using a DependencyProperty field to back a common language runtime (CLR) property. Dependency properties support several advanced Windows Presentation Foundation (WPF) property system features. These features include styles, data binding, inheritance, animation, and default values. If you want properties that you define to support those features, then implement your properties as a dependency property.

Example

The following example shows how to register a dependency property, by calling the Register method. The Register method returns a DependencyProperty instance called a dependency property identifier. The identifier is stored in a static readonly field, and holds the name and characteristics of a dependency property.

The identifier field must follow the naming convention <property name>Property. For instance, if you register a dependency property with the name Location, then the identifier field should be named LocationProperty. If you fail to follow this naming pattern, then WPF designers might not report your property correctly, and aspects of the property system style application might not behave as expected.

In the following example, the name of the dependency property and its CLR accessor is HasFish, so the identifier field is named HasFishProperty. The dependency property type is Boolean and the owner type that registers the dependency property is Aquarium.

You can specify default metadata for a dependency property. This example sets a default value of false for the HasFish dependency property.

public class Aquarium : DependencyObject
{
    public static readonly DependencyProperty HasFishProperty =
        DependencyProperty.Register(
            name: "HasFish",
            propertyType: typeof(bool),
            ownerType: typeof(Aquarium),
            typeMetadata: new FrameworkPropertyMetadata(defaultValue: false));

    public bool HasFish
    {
        get => (bool)GetValue(HasFishProperty);
        set => SetValue(HasFishProperty, value);
    }
}
Public Class Aquarium
    Inherits DependencyObject

    Public Shared ReadOnly HasFishProperty As DependencyProperty =
    DependencyProperty.Register(
        name:="HasFish",
        propertyType:=GetType(Boolean),
        ownerType:=GetType(Aquarium),
        typeMetadata:=New FrameworkPropertyMetadata(defaultValue:=False))

    Public Property HasFish As Boolean
        Get
            Return GetValue(HasFishProperty)
        End Get
        Set(value As Boolean)
            SetValue(HasFishProperty, value)
        End Set
    End Property

End Class

For more information about how and why to implement a dependency property, rather than just backing a CLR property with a private field, see Dependency properties overview.

See also