Dependency​Object Dependency​Object Dependency​Object Dependency​Object Class

Definition

Represents an object that participates in the dependency property system. DependencyObject is the immediate base class of many important UI-related classes, such as UIElement, Geometry, FrameworkTemplate, Style, and ResourceDictionary. For more info on how DependencyObject supports dependency properties, see Dependency properties overview.

public : class DependencyObject : IDependencyObject, IDependencyObject2public class DependencyObject : IDependencyObject, IDependencyObject2Public Class DependencyObject Implements IDependencyObject, IDependencyObject2// This API is not available in Javascript.
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

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 The service potentially acts on the attached property values on those UI elements at run time.

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
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

This example shows a simple dependency property declaration. A call to GetValue constitutes the entirety of the get accessor implementation for the property wrapper of the new dependency property. A call to SetValue constitutes the entirety of the set accessor implementation. 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

Remarks

The DependencyObject class enables dependency property system services on its many derived classes. For more info about the dependency property concept, see Dependency properties overview.

The dependency property system's primary function is to compute the values of properties, and to provide system notification about values that have changed. Another key class that participates in the dependency property system is DependencyProperty. DependencyProperty enables the registration of dependency properties into the property system, whereas DependencyObject as a base class enables objects to use and set the dependency properties.

Here are some notable services and characteristics that DependencyObject provides or supports:

  • Dependency property hosting support for the existing Windows Runtime dependency properties.
  • Custom dependency property hosting support. You register a dependency property by calling the Register method and storing the method's return value as a public static property in your DependencyObject class.
  • Attached property hosting support for the existing Windows Runtime attached properties.
  • Custom attached property hosting support. You register a dependency property for the attached property usage by calling the RegisterAttached method and storing the method's return value as a public static property in your class.
  • Get and Set utility methods for values of any dependency properties that exist on a DependencyObject. You use these when defining custom dependency property "wrappers" and can also use them from app code as an alternative to using existing "wrapper" properties.
  • Advanced-scenario utility for examining metadata or property values (for example GetAnimationBaseValue ).
  • Enforcement of thread affinity to the main UI thread of the Windows Runtime for all DependencyObject instances.
  • The Dispatcher property for advanced threading scenarios. Getting the Dispatcher value provides a reference to a CoreDispatcher object. With the CoreDispatcher, a worker thread can run code that use a DependencyObject but is not on the UI thread, because the CoreDispatcher can defer the execution to an asynchronous operation that won't block or otherwise interfere with the UI thread. See "DependencyObject and threading" section below.
  • Basic data binding and styling support, by enabling properties to be set as expressions to be evaluated at some later point in an object's lifetime. These concepts are explained in more detail in Dependency properties overview. See also Data binding in depth.

DependencyObject and threading

All DependencyObject instances must be created on the UI thread that is associated with the current Window for an app. This is enforced by the system, and there are two important implications of this for your code:

  • Code that uses API from two DependencyObject instances will always be run on the same thread, which is always the UI thread. You don't typically run into threading issues in this scenario.
  • Code that is not running on the main UI thread cannot access a DependencyObject directly because a DependencyObject has thread affinity to the UI thread only. Only code that runs on the UI thread can change or even read the value of a dependency property. For example a worker thread that you've initiated with a .NET Task or an explicit ThreadPool thread won't be able to read dependency properties or call other APIs.

You aren't completely blocked from using a DependencyObject from a worker thread. But you must get a CoreDispatcher object (the value of DependencyObject.Dispatcher ) from a DependencyObject in order to get across the deliberate separation between the app UI thread and any other threads running on the system. The CoreDispatcher exposes the RunAsync method. Call RunAsync to run your awaitable code (an IAsyncAction ). If it's simple code you can use a lambda expression, otherwise you can implement as a delegate (DispatchedHandler ). The system determines a time that your code can be run. Because it's enabling access across threads, DependencyObject.Dispatcher is the only instance API of DependencyObject or any of its subclasses that can be accessed from a non-UI thread without throwing a cross-thread exception. All other DependencyObject APIs throw an exception if you attempt to call them from a worker thread or any other non-UI thread.

Threading issues can usually be avoided in typical UI code. However, devices aren't usually associated with the UI thread. If you are using info obtained from a device to update the UI in real-time, you often must get a CoreDispatcher so that you can update the UI. Services are another case where the code you use to access the service might not be running on the UI thread.

One code scenario where you might encounter DependencyObject -related threading issues if you are defining your own DependencyObject types and you attempt to use them for data sources, or other scenarios where a DependencyObject isn't necessarily appropriate (because the object is not directly related to the UI). For example, you might be attempting perf optimizations with background threads or other worker threads that are changing values of the objects prior to presentation, or in response to a device, service or other external input. Evaluate whether you really need dependency properties for your scenario; maybe standard properties are adequate.

DependencyObject derived classes

DependencyObject is the parent class for several immediately derived classes that are all fundamental to the programming model you use for your app and its XAML UI. Here are some of the notable derived classes:

Constructors

DependencyObject() DependencyObject() DependencyObject() DependencyObject()

Provides base class initialization behavior for DependencyObject derived classes.

protected : DependencyObject()protected DependencyObject()Protected Sub New()// This API is not available in Javascript.

Properties

Dispatcher Dispatcher Dispatcher Dispatcher

Gets the CoreDispatcher that this object is associated with. The CoreDispatcher represents a facility that can access the DependencyObject on the UI thread even if the code is initiated by a non-UI thread.

public : CoreDispatcher Dispatcher { get; }public CoreDispatcher Dispatcher { get; }Public ReadOnly Property Dispatcher As CoreDispatcher// This API is not available in Javascript.
Value
CoreDispatcher CoreDispatcher CoreDispatcher CoreDispatcher

The CoreDispatcher that DependencyObject object is associated with, which represents the UI thread.

Examples

This example shows a usage of Dispatcher for the implicit this of a code-behind file for a Page. This example uses a lambda expression to add the DispatchedHandler implementation. The handler itself is handling the Accelerometer.ReadingChanged event, which won't be executed on the UI thread.

        private async void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                AccelerometerReading reading = e.Reading;
                ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.AccelerationX);
                ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.AccelerationY);
                ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.AccelerationZ);
            });
        }

Remarks

The Dispatcher property provides the CoreDispatcher reference that can be used to marshal calls coming from non-UI threads, using RunAsync and an awaitable function. For more info on awaitable functions, see Call asynchronous APIs in C# or Visual Basic. See also "DependencyObject and threading" section of the DependencyObject reference topic.

A DependencyObject must be created on a UI thread and has affinity to the UI thread. Because it's an entry point that enables getting across threads, DependencyObject.Dispatcher is the only instance API of DependencyObject or any of its subclasses that can be accessed from a non-UI thread without throwing a cross-thread exception. All other DependencyObject APIs throw an exception if you attempt to call them from a worker thread or other non-UI thread.

Specifically, the Dispatcher property gets the CoreDispatcher that is associated with the app UI thread. Running code through the RunAsync method of the CoreDispatcher is necessary if you intend to query or change the value of any dependency property, even if that object isn't yet associated with the XAML visual tree or the visible UI (the visual root of the app window).

Window.Dispatcher also references a CoreDispatcher that is associated with the UI thread. Window.Dispatcher is basically just a wrapper around CoreWindow.Dispatcher so that a Window class has easy access to it.

Note

The connection for a Dispatcher value is not available in a design-time view. This can cause issues if you've created a custom control that uses Dispatcher values and that code is accessed by a design-time environment through code paths that a design view uses, such as constructors and Loaded handlers. If you're writing a custom control and you encounter this issue, consider introducing a guard conditional in your code such as not calling that code when DesignModeEnabled is true.

Methods

ClearValue(DependencyProperty) ClearValue(DependencyProperty) ClearValue(DependencyProperty) ClearValue(DependencyProperty)

Clears the local value of a dependency property.

public : void ClearValue(DependencyProperty dp)public void ClearValue(DependencyProperty dp)Public Function ClearValue(dp As DependencyProperty) As void// This API is not available in Javascript.
Parameters
dp
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The DependencyProperty identifier of the property for which to clear the value.

Remarks

ClearValue is sometimes used as part of a property-changed callback method. For more info, see Custom dependency properties.

See Also

GetAnimationBaseValue(DependencyProperty) GetAnimationBaseValue(DependencyProperty) GetAnimationBaseValue(DependencyProperty) GetAnimationBaseValue(DependencyProperty)

Returns any base value established for a dependency property, which would apply in cases where an animation is not active.

public : PlatForm::Object GetAnimationBaseValue(DependencyProperty dp)public object GetAnimationBaseValue(DependencyProperty dp)Public Function GetAnimationBaseValue(dp As DependencyProperty) As object// This API is not available in Javascript.
Parameters
dp
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the desired dependency property.

Returns
PlatForm::Object object object object

The returned base value.

Remarks

Use GetAnimationBaseValue to get values that might currently be animated but you want to know the value before the animation ran. Note that animations with HoldEnd behavior might not have this same value. For more info on the HoldEnd concept, see Storyboarded animations.

Animations that are used for visual states don't have HoldEnd behavior but do apply an animated value applied while the state is active. For more info, see Storyboarded animations for visual states.

See Also

GetValue(DependencyProperty) GetValue(DependencyProperty) GetValue(DependencyProperty) GetValue(DependencyProperty)

Returns the current effective value of a dependency property from a DependencyObject.

public : PlatForm::Object GetValue(DependencyProperty dp)public object GetValue(DependencyProperty dp)Public Function GetValue(dp As DependencyProperty) As object// This API is not available in Javascript.
Parameters
dp
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The DependencyProperty identifier of the property for which to retrieve the value.

Returns
PlatForm::Object object object object

Returns the current effective value.

Remarks

GetValue obtains the current effective value of a dependency property. The current effective value is determined by using rules of Dependency properties overview.

GetValue is the API you want in most cases if you are using the property system API for obtaining property values. But sometimes you might want to examine other values to see how the dependency property precedence is acting for a given property. If so, you can use one of these API:

  • GetAnimationBaseValue to get values that might currently be animated but you want to know the value before the animation ran. Note that animations with HoldEnd behavior might not have this same value. For more info on the HoldEnd concept, see Storyboarded animations.
  • ReadLocalValue to get the local value, which does not have styles or templates or animations applied. Bindings do count as local values, but depending on when you call ReadLocalValue, the acting binding context might not be available yet, so you won't get the same value as would be applied at run time. For more info on dependency property precedence and other property system utility API, see Dependency properties overview.
See Also

ReadLocalValue(DependencyProperty) ReadLocalValue(DependencyProperty) ReadLocalValue(DependencyProperty) ReadLocalValue(DependencyProperty)

Returns the local value of a dependency property, if a local value is set.

public : PlatForm::Object ReadLocalValue(DependencyProperty dp)public object ReadLocalValue(DependencyProperty dp)Public Function ReadLocalValue(dp As DependencyProperty) As object// This API is not available in Javascript.
Parameters
dp
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The DependencyProperty identifier of the property for which to retrieve the local value.

Returns
PlatForm::Object object object object

Returns the local value, or returns the sentinel value UnsetValue if no local value is set.

Remarks

The local value is not always the effective value. For more info, see Dependency properties overview.

See Also

RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback) RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback) RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback) RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback)

Registers a notification function for listening to changes to a specific DependencyProperty on this DependencyObject instance.

public : long RegisterPropertyChangedCallback(DependencyProperty dp, DependencyPropertyChangedCallback callback)public long RegisterPropertyChangedCallback(DependencyProperty dp, DependencyPropertyChangedCallback callback)Public Function RegisterPropertyChangedCallback(dp As DependencyProperty, callback As DependencyPropertyChangedCallback) As long// This API is not available in Javascript.
Parameters
dp
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The dependency property identifier of the property to register for property-changed notification.

callback
DependencyPropertyChangedCallback DependencyPropertyChangedCallback DependencyPropertyChangedCallback DependencyPropertyChangedCallback

A callback based on the DependencyPropertyChangedCallback delegate, which the system invokes when the value of the specified property changes.

Returns
long long long long

A token that represents the callback, used to identify the callback in calls to UnregisterPropertyChangedCallback.

Examples

This example shows how to use a DependencyPropertyChangedCallback delegate to listen for changes to the Tag property on a TextBlock.

<TextBlock x:Name="textBlock1" Text="Hello, world"/>
long tagToken;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    long tagToken = textBlock1.RegisterPropertyChangedCallback(TextBlock.TagProperty, tbTagChangedCallback);
    base.OnNavigatedTo(e);

    textBlock1.Tag = "name";
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    textBlock1.UnregisterPropertyChangedCallback(TextBlock.TagProperty, tagToken);
    base.OnNavigatedFrom(e);
}

private void tbTagChangedCallback(DependencyObject sender, DependencyProperty dp)
{
    if (dp == TextBlock.TagProperty)
    {
       // These lines produce the same result.
       System.Diagnostics.Debug.WriteLine("The tag has been set to " + ((TextBlock)sender).Tag);
       System.Diagnostics.Debug.WriteLine("The tag has been set to " + sender.GetValue(dp));
    }
}

Remarks

Use RegisterPropertyChangedCallback to get property-changed notification for dependency properties that are already defined as part of the Windows Runtime. This is useful for properties where were isn't already a corresponding Windows Runtime event that tracks changes. For example, FrameworkElement.Tag is an existing Windows Runtime dependency property, and your app could track when that property's value changes because some external input (like a data binding) has changed that property's runtime value on a particular object instance that's part of your app UI.

To unregister the callback, call UnregisterPropertyChangedCallback and pass in the token returned by this method.

You don't typically use RegisterPropertyChangedCallback for notifications on a custom dependency property, because custom dependency properties already have a way to register a property-changed handler that provides more data in the event args. For more info, see Custom dependency properties.

See Also

SetValue(DependencyProperty, Object) SetValue(DependencyProperty, Object) SetValue(DependencyProperty, Object) SetValue(DependencyProperty, Object)

Sets the local value of a dependency property on a DependencyObject.

public : void SetValue(DependencyProperty dp, PlatForm::Object value)public void SetValue(DependencyProperty dp, Object value)Public Function SetValue(dp As DependencyProperty, value As Object) As void// This API is not available in Javascript.
Parameters
dp
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier of the dependency property to set.

value
PlatForm::Object Object Object Object

The new local value.

Remarks

If the provided value type does not match the type that is declared for the dependency property as it was originally registered, an exception is thrown.

Not all Windows Runtime properties as used by XAML are dependency properties. A DependencyProperty identifier needs to exist and it must be available as a public property of an owning object, typically the object that registered the property.

For app user-code, calling SetValue is not typically necessary. Usually, a Windows Runtime dependency property or a custom dependency property has a conventional property that wraps it, and you can just set the property value through a conventional dotted usage. Cases where you might still use SetValue are:

  • You are defining a custom dependency property. You will call SetValue as part of defining your own property set accessor for a conventional property usage. For more info, see Custom dependency properties.
  • You are defining a callback or are in some other scope where you are already being passed a DependencyProperty identifier, and it is possible that more than one dependency property exists that you might want to interact with in that scope. In these cases it is probably simpler to call SetValue, passing the identifier.
See Also

UnregisterPropertyChangedCallback(DependencyProperty, Int64) UnregisterPropertyChangedCallback(DependencyProperty, Int64) UnregisterPropertyChangedCallback(DependencyProperty, Int64) UnregisterPropertyChangedCallback(DependencyProperty, Int64)

Cancels a change notification that was previously registered by calling RegisterPropertyChangedCallback.

public : void UnregisterPropertyChangedCallback(DependencyProperty dp, long token)public void UnregisterPropertyChangedCallback(DependencyProperty dp, Int64 token)Public Function UnregisterPropertyChangedCallback(dp As DependencyProperty, token As Int64) As void// This API is not available in Javascript.
Parameters
dp
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The dependency property identifier of the property to unregister for property-changed notification.

token
long Int64 Int64 Int64

A token that represents the callback (returned by RegisterPropertyChangedCallback ).

See Also

See Also