DependencyObject Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Represents an object that participates in the dependency property system.
public ref class DependencyObject
/// [Windows.Foundation.Metadata.ContractVersion(Microsoft.UI.Xaml.WinUIContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class DependencyObject
[Windows.Foundation.Metadata.ContractVersion(typeof(Microsoft.UI.Xaml.WinUIContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public class DependencyObject
Public Class DependencyObject
- Inheritance
- Derived
- Attributes
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 Buoyancy { Floats, Sinks, Drifts }
public static readonly DependencyProperty BuoyancyProperty = DependencyProperty.RegisterAttached(
"Buoyancy",
typeof(Buoyancy),
typeof(AquariumServices),
new PropertyMetadata(Buoyancy.Floats)
);
public static void SetBuoyancy(DependencyObject element, Buoyancy value)
{
element.SetValue(BuoyancyProperty, value);
}
public static Buoyancy GetBuoyancy(DependencyObject element)
{
return (Buoyancy)element.GetValue(BuoyancyProperty);
}
}
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;
}
}
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); }
}
}
Remarks
The DependencyObject
class enables dependency property system services on its many derived classes, and 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.
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
andSet
utility methods for values of any dependency properties that exist on aDependencyObject
. 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 DispatcherQueue property for advanced threading scenarios. The
DispatcherQueue
lets a worker thread run code that uses aDependencyObject
but is not on the UI thread, because it 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 aDependencyObject
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 DispatcherQueue object (the value of DependencyObject.DispatcherQueue) 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 DispatcherQueue
exposes the TryEnqueue method to run your awaitable code. Because it's enabling access across threads, DependencyObject.DispatcherQueue
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 DispatcherQueue
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:
- UIElement: The base class for most visual objects that can process input in the UI. FrameworkElement is further in this hierarchy, as is Control, so there are hundreds of controls and other classes in the Windows Runtime that all have the UIElement class in their class hierarchies.
- XAML style system support classes: FrameworkTemplate (parent of ControlTemplate, DataTemplate, ItemsPanelTemplate), Style, SetterBase (parent of Setter), ToolTipTemplateSettings and other TemplateSettings.
- Visual state model: Transition, VisualState, VisualStateGroup, VisualStateManager, VisualTransition.
- Data binding support: BindingBase (parent of Binding), CollectionViewSource, PropertyPath, RelativeSource.
- Storyboarded animations: Timeline (parent of Storyboard, typed animations, theme animations), typed keyframes (like ColorKeyFrame), KeySpline, EasingFunctionBase.
- XAML graphics and rendering primitives: Brush, Geometry, GeneralTransform, GradientStop, PathFigure, PathSegment, Projection.
- Imaging and render surface interop: ImageSource (parent of BitmapSource, RenderTargetBitmap, SurfaceImageSource and others).
- Window: represents the main app window.
- FlyoutBase (parent of Flyout and MenuFlyout).
- ResourceDictionary: defines keyed resources in XAML.
- TextElement: parent of Block and Inline, these in turn are base classes for text elements used for TextBlock content or the rich text elements.
- AutomationPeer: base class for Microsoft UI Automation peers that represent XAML controls to a Microsoft UI Automation listener. Also, IRawElementProviderSimple.
- Miscellaneous: CacheMode, ColumnDefinition, DependencyObjectCollection, InputScope, InputScopeName, PageStackEntry, PrintDocument, RowDefinition, TriggerAction, TriggerBase.
Constructors
DependencyObject() |
Provides base class initialization behavior for DependencyObject derived classes. |
Properties
Dispatcher |
Always returns |
DispatcherQueue |
Gets the |
Methods
ClearValue(DependencyProperty) |
Clears the local value of a dependency property. |
GetAnimationBaseValue(DependencyProperty) |
Returns any base value established for a dependency property, which would apply in cases where an animation is not active. |
GetValue(DependencyProperty) |
Returns the current effective value of a dependency property from a DependencyObject. |
ReadLocalValue(DependencyProperty) |
Returns the local value of a dependency property, if a local value is set. |
RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback) |
Registers a notification function for listening to changes to a specific DependencyProperty on this DependencyObject instance. |
SetValue(DependencyProperty, Object) |
Sets the local value of a dependency property on a DependencyObject. |
UnregisterPropertyChangedCallback(DependencyProperty, Int64) |
Cancels a change notification that was previously registered by calling RegisterPropertyChangedCallback. |