DependencyObject DependencyObject DependencyObject Class

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.

Syntax

Declaration

public class DependencyObjectpublic class DependencyObjectPublic Class DependencyObject

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:

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 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(Windows.UI.Core.CoreDispatcherPriority,Windows.UI.Core.DispatchedHandler) method. Call RunAsync(Windows.UI.Core.CoreDispatcherPriority,Windows.UI.Core.DispatchedHandler) 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, 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:

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

[TODO:AUTO_SNIPPET (SAMPLE_ID:DOandDP)(SNIPPET_ID:DOCheckClear)]This example shows a simple dependency property declaration. A call to GetValue(Windows.UI.Xaml.DependencyProperty) constitutes the entirety of the get accessor implementation for the property wrapper of the new dependency property. A call to SetValue(Windows.UI.Xaml.DependencyProperty,System.Object) constitutes the entirety of the set accessor implementation. For more examples, see Custom dependency properties.

[TODO:AUTO_SNIPPET (SAMPLE_ID:DOandDP)(SNIPPET_ID:DOSimpleDP)]

Properties summary

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.

Methods summary

Clears the local value of a dependency property.

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

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

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

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

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

Cancels a change notification that was previously registered by calling RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback).

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

    Property Value

    Remarks

    The Dispatcher property provides the CoreDispatcher reference that can be used to marshal calls coming from non-UI threads, using RunAsync(Windows.UI.Core.CoreDispatcherPriority,Windows.UI.Core.DispatchedHandler) 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, 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(Windows.UI.Core.CoreDispatcherPriority,Windows.UI.Core.DispatchedHandler) 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).

    Dispatcher also references a CoreDispatcher that is associated with the UI thread. Dispatcher is basically just a wrapper around 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.

    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 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);
                });
            }
    

Methods

  • ClearValue(Windows.UI.Xaml.DependencyProperty)
    ClearValue(Windows.UI.Xaml.DependencyProperty)
    ClearValue(Windows.UI.Xaml.DependencyProperty)
    ClearValue(Windows.UI.Xaml.DependencyProperty)

    Clears the local value of a dependency property.

    public void ClearValue(Windows.UI.Xaml.DependencyProperty)public void ClearValue(Windows.UI.Xaml.DependencyProperty)Public Function ClearValue(Windows.UI.Xaml.DependencyProperty) As void

    Parameters

    Remarks

    ClearValue(Windows.UI.Xaml.DependencyProperty) is sometimes used as part of a property-changed callback method. For more info, see Custom dependency properties.

  • GetAnimationBaseValue(Windows.UI.Xaml.DependencyProperty)
    GetAnimationBaseValue(Windows.UI.Xaml.DependencyProperty)
    GetAnimationBaseValue(Windows.UI.Xaml.DependencyProperty)
    GetAnimationBaseValue(Windows.UI.Xaml.DependencyProperty)

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

    public object GetAnimationBaseValue(Windows.UI.Xaml.DependencyProperty)public object GetAnimationBaseValue(Windows.UI.Xaml.DependencyProperty)Public Function GetAnimationBaseValue(Windows.UI.Xaml.DependencyProperty) As object

    Parameters

    Returns

    • object
      object
      object

      The returned base value.

    Remarks

    Use GetAnimationBaseValue(Windows.UI.Xaml.DependencyProperty) 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.

  • GetValue(Windows.UI.Xaml.DependencyProperty)
    GetValue(Windows.UI.Xaml.DependencyProperty)
    GetValue(Windows.UI.Xaml.DependencyProperty)
    GetValue(Windows.UI.Xaml.DependencyProperty)

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

    public object GetValue(Windows.UI.Xaml.DependencyProperty)public object GetValue(Windows.UI.Xaml.DependencyProperty)Public Function GetValue(Windows.UI.Xaml.DependencyProperty) As object

    Parameters

    Returns

    • object
      object
      object

      Returns the current effective value.

    Remarks

    GetValue(Windows.UI.Xaml.DependencyProperty) obtains the current effective value of a dependency property. The current effective value is determined by using rules of Dependency properties overview.

    GetValue(Windows.UI.Xaml.DependencyProperty) 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:

  • ReadLocalValue(Windows.UI.Xaml.DependencyProperty)
    ReadLocalValue(Windows.UI.Xaml.DependencyProperty)
    ReadLocalValue(Windows.UI.Xaml.DependencyProperty)
    ReadLocalValue(Windows.UI.Xaml.DependencyProperty)

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

    public object ReadLocalValue(Windows.UI.Xaml.DependencyProperty)public object ReadLocalValue(Windows.UI.Xaml.DependencyProperty)Public Function ReadLocalValue(Windows.UI.Xaml.DependencyProperty) As object

    Parameters

    Returns

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

  • RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback)
    RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback)
    RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback)
    RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback)

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

    public long RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback)public long RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback)Public Function RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback) As long

    Parameters

    Returns

    Remarks

    Use RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback) 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, 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(Windows.UI.Xaml.DependencyProperty,System.Int64) and pass in the token returned by this method.

    You don't typically use RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback) 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.

    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));
        }
    }
    
  • SetValue(Windows.UI.Xaml.DependencyProperty,System.Object)
    SetValue(Windows.UI.Xaml.DependencyProperty,System.Object)
    SetValue(Windows.UI.Xaml.DependencyProperty,System.Object)
    SetValue(Windows.UI.Xaml.DependencyProperty,System.Object)

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

    public void SetValue(Windows.UI.Xaml.DependencyProperty,System.Object)public void SetValue(Windows.UI.Xaml.DependencyProperty,System.Object)Public Function SetValue(Windows.UI.Xaml.DependencyProperty,System.Object) As void

    Parameters

    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(Windows.UI.Xaml.DependencyProperty,System.Object) 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(Windows.UI.Xaml.DependencyProperty,System.Object) are:

  • UnregisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,System.Int64)
    UnregisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,System.Int64)
    UnregisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,System.Int64)
    UnregisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,System.Int64)

    Cancels a change notification that was previously registered by calling RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback).

    public void UnregisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,System.Int64)public void UnregisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,System.Int64)Public Function UnregisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,System.Int64) As void

    Parameters

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.ComposableAttribute
Windows.Foundation.Metadata.ThreadingAttribute
Windows.Foundation.Metadata.WebHostHiddenAttribute
Windows.Foundation.Metadata.ContractVersionAttribute

Details

Assembly

Windows.UI.Xaml.dll