Dependency​Property Dependency​Property Dependency​Property Class

Definition

Represents a dependency property that is registered with the dependency property system. Dependency properties provide support for value expressions, data binding, animation, and property change notification. For more info on how DependencyProperty values serve as identifiers for dependency properties, see Dependency properties overview.

public sealed class DependencyProperty : IDependencyPropertypublic sealed class DependencyProperty : IDependencyPropertyPublic NotInheritable Class DependencyProperty Implements IDependencyProperty
See Remarks
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

Remarks

Dependency property concepts are covered in detail in the topic Dependency properties overview.

Instances of DependencyProperty are often referenced in the documentation as dependency property identifiers. The identifiers provide a way to refer to a dependency property that was registered to a particular DependencyObject owner type. When the owner type registers the property, the owner type exposes the DependencyProperty instance as the identifier, which is a static member of the owner class.

The owner DependencyObject provides the property store for the dependency property. When working with a dependency property in code, you might use a DependencyProperty identifiers as input for calls to property system methods such as SetValue. However, in most cases, getting or setting a dependency property is simpler by getting or setting the wrapper; this concept is explained in Dependency properties overview.

DependencyProperty supports a native conversion for XAML attribute syntax for filling values, which is used when a Setter specifies its Property value. This conversion uses an ownerTypeName.propertyName form for the input string.

Note

A related syntax that can also be used to specify a property by name and is required by certain data and animation API is the property path syntax. A property path can be used to reference the structure of a class that has properties and the value of that property. For more info, see Property-path syntax.

Tip

If you are programming using a Microsoft .NET language (C# or Microsoft Visual Basic), the TypeName type projects as System.Type. When programming using C#, it is common to use the typeof operator to get references to the System.Type of a type. In Microsoft Visual Basic, use GetType. If you're using Visual C++ component extensions (C++/CX)), where you'll need to create a TypeName helper struct, you can use the typeid component extension.

The Windows Runtime implements the XAML attached property language feature with DependencyProperty identifiers and property storage on a DependencyObject. For more info, see Attached properties overview.

Custom dependency properties

If you want properties on your custom types to support value expressions, data binding, or animation, you should back the properties with a dependency property following these guidelines:

  • Register a dependency property using the Register method, which returns a DependencyProperty. This is your dependency property identifier. You should expose this object as an accessible static read-only property in your class. By convention, the name of this DependencyProperty identifier field should end with "Property".
  • During registration, you can provide PropertyMetadata for the property to further define the property's behaviors.
  • Provide get and set accessors for the property: these are the property wrappers, and will simplify access to your property for all callers.

XAML references to a dependency property name

Some properties that are typically set in XAML markup use DependencyProperty as their value. For example, you set Setter.Property in XAML. To set such a property in XAML, you specify the name of the dependency property as the attribute value.

For Setter.Property the type from which you are referencing a dependency property name is already scoped by the TargetType of the Style where the Setter exists. For a dependency property on the TargetType object, you can specify a Setter.Property value using the simple name of the dependency property. For example, if you have a Style that targets a Slider, and you want to style the Orientation property, the Property attribute value can be just "Orientation". Simple names also work so long as the dependency property came from a class in the deeper inheritance of the target type. For example, to style the Visibility property in the Style for a Slider, a Property attribute value of "Visibility" will work. In that case Visibility was defined by UIElement, but inherits to Slider.

You can also use Setter.Property to reference an attached property name. For the attribute value, use the form AttachedPropertyOwner.AttachedPropertyName, just like you'd use to set that attached property as an attribute in XAML. For example, here is a Setter that sets the attached property AutomationProperties.ItemType in a Style: <Setter Property="AutomationProperties.ItemType" Value="Navigation Button"/>

Note

The name of a dependency property is not the name of the DependencyProperty static property identifier. It's the name string that the property is registered with, and the name that's the typical usage name for that property in Windows Runtime programming when exposed by Microsoft IntelliSense and the reference documentation. In other words, you don't want the string you specify for Setter.Property in XAML to end with "Property" (except for a few rare cases where the dependency property actually does contain the suffix "Property").

Using a DependencyProperty (dependency property identifier) in code

There are several methods that are utility methods for the Windows Runtime property system that use a DependencyProperty value as an input parameter. These include:

Examples

This example shows a basic usage where a DependencyProperty is established as a public static member of a class. This is done by calling Register and storing the return value as a member of the class. For more examples, see Custom dependency properties.

public class Fish : Control
{
    public static readonly DependencyProperty SpeciesProperty =
    DependencyProperty.Register(
    "Species",
    typeof(String),
    typeof(Fish), null
    );
    public string Species
    {
        get { return (string)GetValue(SpeciesProperty); }
        set { SetValue(SpeciesProperty, (string)value); }
    }
}
Public Class Fish
    Inherits Control

    Public Shared ReadOnly SpeciesProperty As DependencyProperty = _
    DependencyProperty.Register(
    "Species", _
    GetType(String), _
    GetType(Fish), _
    Nothing)
    Public Property Species As String
        Get
            Species = CType(GetValue(SpeciesProperty), String)
        End Get
        Set(value As String)
            SetValue(SpeciesProperty, value)
        End Set
    End Property
End Class

A Visual C++ component extensions (C++/CX) example isn't shown here because it must be factored completely differently than the Microsoft .NET examples, and involves several different code files. See examples in Custom dependency properties.

Properties

UnsetValue UnsetValue UnsetValue

Specifies a static value that is used by the property system rather than null to indicate that the property exists, but does not have its value set by the property system or by any app code.

public static PlatForm::Object UnsetValue { get; }public static object UnsetValue { get; }Public Static ReadOnly Property UnsetValue As object
Value
object object object

The sentinel value for an unset value.

Attributes

Remarks

UnsetValue is a sentinel value that is used for scenarios where the dependency property system is unable to determine a requested dependency property value. UnsetValue is used rather than null, because null is a valid property value for most reference-type values, and is a frequently used DefaultValue in metadata for a dependency property.

UnsetValue is never returned out of a DependencyObject.GetValue call. When you call DependencyObject.GetValue for a dependency property, one of these conditions is always true:

  • A dependency property has a default value established in metadata and that value is returned. This value might come from the property metadata's DefaultValue. This might be null.
  • Some other value was established through value precedence (for example a style was applied, or a Binding was evaluated), and the default value is no longer relevant. Even though specifically set, this still might be null. For more info on value precedence, see Dependency properties overview.

DependencyObject.ReadLocalValue returns UnsetValue when the requested property has not been locally set.

Note

Do not register a dependency property with the default value of UnsetValue. This will be confusing for property consumers and will have unintended consequences within the property system.

UnsetValue should be returned from an IValueConverter implementation that provides conversion in a data binding to a dependency property, in any case where the converter is unable to convert a source value. Converters shouldn't throw exceptions for that case in IValueConverter.Convert, these will surface as run-time exceptions that you'd need to add handling for in UnhandledException or worse yet appear to users as actual run-time exceptions. Converter implementations should follow the general binding pattern that any failed binding does nothing and does not provide a value, and UnsetValue rather than null is the sentinel value for that case that the binding engine understands. For more info, see Data binding in depth.

Examples

This example checks for an existing local value with ReadLocalValue. If there is a local value, as indicated by not returning UnsetValue, then the existing local value is removed by calling ClearValue.

public static bool ClearSetProperty(DependencyObject targetObject, DependencyProperty targetDP)
{
    if (targetObject == null || targetDP == null)
    {
        throw new ArgumentNullException();
    }
    object localValue = targetObject.ReadLocalValue(targetDP);
    if (localValue == DependencyProperty.UnsetValue)
    {
        return false;
    }
    else
    {
        targetObject.ClearValue(targetDP);
        return true;
    }
}
Public Shared Function ClearSetProperty(targetObject As DependencyObject, targetDP As DependencyProperty) As Boolean
    If targetObject Is Nothing Or targetDP Is Nothing Then
        Throw New ArgumentNullException()
    End If
    Dim localValue As Object = targetObject.ReadLocalValue(targetDP)
    If localValue = DependencyProperty.UnsetValue Then
        ClearSetProperty = False
    Else
        targetObject.ClearValue(targetDP)
        ClearSetProperty = True
    End If
End Function
See Also

Methods

GetMetadata(TypeName) GetMetadata(TypeName) GetMetadata(TypeName)

Retrieves the property metadata value for the dependency property as registered to a type. You specify the type you want info from as a type reference.

public PropertyMetadata GetMetadata(TypeName forType)public PropertyMetadata GetMetadata(TypeName forType)Public Function GetMetadata(forType As TypeName) As PropertyMetadata
Parameters
forType
TypeName TypeName TypeName

The name of the specific type from which to retrieve the dependency property metadata, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).

Returns

A property metadata object.

Attributes

Remarks

Examples

This example implements a utility method that reports the default value of a given dependency property as it exists in FrameworkElement, based on the default value registered and stored in the metadata.

public static object GetDefaultValueForFrameworkDP(DependencyProperty dpIdentifier)
{
    PropertyMetadata metadataInfo = dpIdentifier.GetMetadata(typeof(FrameworkElement));
    return metadataInfo.DefaultValue;
}
Public Shared Function GetDefaultValueForFrameworkDP(dpIdentifier As DependencyProperty) As Object
    Dim metadataInfo As PropertyMetadata = dpIdentifier.GetMetadata(GetType(FrameworkElement))
    GetDefaultValueForFrameworkDP = metadataInfo.DefaultValue
End Function
See Also

Register(String, TypeName, TypeName, PropertyMetadata) Register(String, TypeName, TypeName, PropertyMetadata) Register(String, TypeName, TypeName, PropertyMetadata)

Registers a dependency property with the specified property name, property type, owner type, and property metadata for the property. Use this method when defining or initializing a DependencyObject derived class that will own the registered dependency property.

public static DependencyProperty Register(String name, TypeName propertyType, TypeName ownerType, PropertyMetadata typeMetadata)public static DependencyProperty Register(String name, TypeName propertyType, TypeName ownerType, PropertyMetadata typeMetadata)Public Static Function Register(name As String, propertyType As TypeName, ownerType As TypeName, typeMetadata As PropertyMetadata) As DependencyProperty
Parameters
name
System.String System.String System.String

The name of the dependency property to register.

propertyType
TypeName TypeName TypeName

The type of the property, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).

ownerType
TypeName TypeName TypeName

The owner type that is registering the dependency property, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).

typeMetadata
PropertyMetadata PropertyMetadata PropertyMetadata

A property metadata instance. This can contain a PropertyChangedCallback implementation reference.

Returns

A dependency property identifier that typically is stored in a public static read-only field in your DependencyObject derived class. The identifier is then used both by your own code and any third-party user code to reference the dependency property later, for operations such as setting its value programmatically or attaching a Binding in code.

Attributes

Remarks

How to register a custom dependency property is described in detail (with examples) in the topic Custom dependency properties.

Registering a dependency property is typically something that you only do when an app first starts or DependencyObject derived classes defined by your app code are first used. You need to register the dependency properties early in the app lifetime to assure that other code and XAML in your app don't try to use the dependency properties before they are registered and available. Exactly how and when to register varies, based on the programming language. For C# or Microsoft Visual Basic it's common to register dependency properties during the static class initialization of the class that owns the dependency property. That way any code or XAML that initializes the instance will invoke that static construction and register the dependency property. For Visual C++ component extensions (C++/CX)), static class initialization isn't an available technique, so you typically must define an app-wide helper method that registers all the custom dependency properties that your app intends to use, as part of the Application object initialization. For examples of how and when to register custom dependency properties, including some special techniques that are needed for Visual C++ component extensions (C++/CX), see Custom dependency properties.

See Also

RegisterAttached(String, TypeName, TypeName, PropertyMetadata) RegisterAttached(String, TypeName, TypeName, PropertyMetadata) RegisterAttached(String, TypeName, TypeName, PropertyMetadata)

Registers an attached dependency property with the specified property name, property type, owner type, and property metadata for the property.

public static DependencyProperty RegisterAttached(String name, TypeName propertyType, TypeName ownerType, PropertyMetadata defaultMetadata)public static DependencyProperty RegisterAttached(String name, TypeName propertyType, TypeName ownerType, PropertyMetadata defaultMetadata)Public Static Function RegisterAttached(name As String, propertyType As TypeName, ownerType As TypeName, defaultMetadata As PropertyMetadata) As DependencyProperty
Parameters
name
System.String System.String System.String

The name of the dependency property to register.

propertyType
TypeName TypeName TypeName

The type of the property, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).

ownerType
TypeName TypeName TypeName

The owner type that is registering the dependency property, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).

defaultMetadata
PropertyMetadata PropertyMetadata PropertyMetadata

A property metadata instance. This can contain a PropertyChangedCallback implementation reference.

Returns

A dependency property identifier that should be used to set the value of a public static read-only field in your class. That identifier is then used to reference the attached property later, for operations such as setting its value programmatically or attaching a Binding.

Attributes

Remarks

Examples

This example defines a class that derives from DependencyObject, and defines an attached property along with the identifier field. The scenario for this class is that it is a service class that declares an attached property that other UI elements can set in XAML, and the service potentially acts on the attached property values on those UI elements at run time. For more examples, see Custom attached properties.

public abstract class AquariumServices : DependencyObject
{
    public enum Bouyancy {Floats,Sinks,Drifts}

    public static readonly DependencyProperty BouyancyProperty = DependencyProperty.RegisterAttached(
      "Bouyancy",
      typeof(Bouyancy),
      typeof(AquariumServices),
      new PropertyMetadata(Bouyancy.Floats)
    );
    public static void SetBouyancy(DependencyObject element, Bouyancy value)
    {
        element.SetValue(BouyancyProperty, value);
    }
    public static Bouyancy GetBouyancy(DependencyObject element)
    {
        return (Bouyancy)element.GetValue(BouyancyProperty);
    }
}
Public Class AquariumServices
    Inherits DependencyObject
    Public Enum Bouyancy
        Floats
        Sinks
        Drifts
    End Enum

    Public Shared ReadOnly BouyancyProperty As DependencyProperty = _
          DependencyProperty.RegisterAttached(
          "Bouyancy", _
          GetType(Bouyancy), _
          GetType(AquariumServices), _
          New PropertyMetadata(Bouyancy.Floats))


    Public Sub SetBouyancy(element As DependencyObject, value As Bouyancy)
        element.SetValue(BouyancyProperty, value)
    End Sub
    Public Function GetBouyancy(element As DependencyObject) As Bouyancy
        GetBouyancy = CType(element.GetValue(BouyancyProperty), Bouyancy)
    End Function
End Class
See Also

See Also