Share via


Resources Overview

This overview explains how to use WPF resources as a simple way to reuse commonly defined objects and values. This overview focuses on how to use resources in XAML. You can also create and access resources by using code, or interchangeably between code and Extensible Application Markup Language (XAML). For more information, see Resources and Code.

This topic contains the following sections.

  • Using Resources in XAML
  • Static and Dynamic Resources
  • Styles, DataTemplates, and Implicit Keys
  • Related Topics

Using Resources in XAML

The following example defines a SolidColorBrush as a resource on the root element of a page. The example then references the resource and uses it to set properties of several child elements, including an Ellipse, a TextBlock, and a Button.

<Page Name="root"
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
>
  <Page.Resources>
    <SolidColorBrush x:Key="MyBrush" Color="Gold"/>
    <Style TargetType="Border" x:Key="PageBackground">
      <Setter Property="Background" Value="Blue"/>
    </Style>
    <Style TargetType="TextBlock" x:Key="TitleText">
      <Setter Property="Background" Value="Blue"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
      <Setter Property="FontSize" Value="18"/>
      <Setter Property="Foreground" Value="#4E87D4"/>
      <Setter Property="FontFamily" Value="Trebuchet MS"/>
      <Setter Property="Margin" Value="0,40,10,10"/>
    </Style>
    <Style TargetType="TextBlock" x:Key="Label">
      <Setter Property="DockPanel.Dock" Value="Right"/>
      <Setter Property="FontSize" Value="8"/>
      <Setter Property="Foreground" Value="{StaticResource MyBrush}"/>
      <Setter Property="FontFamily" Value="Arial"/>
      <Setter Property="FontWeight" Value="Bold"/>
      <Setter Property="Margin" Value="0,3,10,0"/>
    </Style>
  </Page.Resources>
  <StackPanel>
    <Border Style="{StaticResource PageBackground}">
      <DockPanel>
        <TextBlock Style="{StaticResource TitleText}">Title</TextBlock>
        <TextBlock Style="{StaticResource Label}">Label</TextBlock>
        <TextBlock DockPanel.Dock="Top" HorizontalAlignment="Left" FontSize="36" Foreground="{StaticResource MyBrush}" Text="Text" Margin="20" />
        <Button DockPanel.Dock="Top" HorizontalAlignment="Left" Height="30" Background="{StaticResource MyBrush}" Margin="40">Button</Button>
        <Ellipse DockPanel.Dock="Top" HorizontalAlignment="Left" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="40" />
      </DockPanel>
    </Border>
  </StackPanel>
</Page>


Every framework-level element (FrameworkElement or FrameworkContentElement) has a Resources property, which is the property that contains the resources (as a ResourceDictionary) that a resource defines. You can define resources on any element. However, resources are most often defined on the root element, which is Page in the example.

Each resource in a resource dictionary must have a unique key. When you define resources in markup, you assign the unique key through the x:Key Directive. Typically, the key is a string; however, you can also set it to other object types by using the appropriate markup extensions. Nonstring keys for resources are used by certain feature areas in WPF, notably for styles, component resources, and data styling.

After you define a resource, you can reference the resource to be used for a property value by using a resource markup extension syntax that specifies the key name, for example:

<Button Background="{StaticResource MyBrush}"/>
<Ellipse Fill="{StaticResource MyBrush}"/>

In the preceding example, when the XAML loader processes the value {StaticResource MyBrush} for the Background property on Button, the resource lookup logic first checks the resource dictionary for the Button element. If Button does not have a definition of the resource key MyBrush (it does not; its resource collection is empty), the lookup next checks the parent element of Button, which is Page. Thus, when you define a resource on the Page root element, all the elements in the logical tree of the Page can access it, and you can reuse the same resource for setting the value of any property that accepts the Type that the resource represents. In the previous example, the same MyBrush resource sets two different properties: the Background of a Button, and the Fill of a Rectangle.

Static and Dynamic Resources

A resource can be referenced as either a static resource or a dynamic resource. This is done by using either the StaticResource Markup Extension or the DynamicResource Markup Extension. A markup extension is a feature of XAML whereby you can specify an object reference by having the markup extension process the attribute string and return the object to a XAML loader. For more information about markup extension behavior, see Markup Extensions and WPF XAML.

When you use a markup extension, you typically provide one or more parameters in string form that are processed by that particular markup extension, rather than being evaluated in the context of the property being set. The StaticResource Markup Extension processes a key by looking up the value for that key in all available resource dictionaries. This happens during loading, which is the point in time when the loading process needs to assign the property value that takes the static resource reference. The DynamicResource Markup Extension instead processes a key by creating an expression, and that expression remains unevaluated until the application is actually run, at which time the expression is evaluated and provides a value.

When you reference a resource, the following considerations can influence whether you use a static resource reference or a dynamic resource reference:

  • The overall design of how you create the resources for your application (per page, in the application, in loose XAML, in a resource only assembly).

  • The application functionality: is updating resources in real time part of your application requirements?

  • The respective lookup behavior of that resource reference type.

  • The particular property or resource type, and the native behavior of those types.

Static Resources

Static resource references work best for the following circumstances:

  • Your application design concentrates most of all of its resources into page or application level resource dictionaries. Static resource references are not reevaluated based on runtime behaviors such as reloading a page, and therefore there can be some performance benefit to avoiding large numbers of dynamic resource references when they are not necessary per your resource and application design.

  • You are setting the value of a property that is not on a DependencyObject or a Freezable.

  • You are creating a resource dictionary that will be compiled into a DLL, and packaged as part of the application or shared between applications.

  • You are creating a theme for a custom control, and are defining resources that are used within the themes. For this case, you typically do not want the dynamic resource reference lookup behavior, you instead want the static resource reference behavior so that the lookup is predictable and self-contained to the theme. With a dynamic resource reference, even a reference within a theme is left unevaluated until runtime, and there is a chance that when the theme is applied, some local element will redefine a key that your theme is trying to reference, and the local element will fall prior to the theme itself in the lookup. If that happens, your theme will not behave in an expected manner.

  • You are using resources to set large numbers of dependency properties. Dependency properties have effective value caching as enabled by the property system, so if you provide a value for a dependency property that can be evaluated at load time, the dependency property does not have to check for a reevaluated expression and can return the last effective value. This technique can be a performance benefit.

  • You want to change the underlying resource for all consumers, or you want to maintain separate writable instances for each consumer by using the x:Shared Attribute.

Static resource lookup behavior

  1. The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.

  2. The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.

  3. Next, application resources are checked. Application resources are those resources within the resource dictionary that is defined by the Application object for your WPF application.

Static resource references from within a resource dictionary must reference a resource that has already been defined lexically before the resource reference. Forward references cannot be resolved by a static resource reference. For this reason, if you use static resource references, you must design your resource dictionary structure such that resources intended for by-resource use are defined at or near the beginning of each respective resource dictionary.

Static resource lookup can extend into themes, or into system resources, but this is supported only because the XAML loader defers the request. The deferral is necessary so that the runtime theme at the time the page loads applies properly to the application. However, static resource references to keys that are known to only exist in themes or as system resources are not recommended. This is because such references are not reevaluated if the theme is changed by the user in realtime. A dynamic resource reference is more reliable when you request theme or system resources. The exception is when a theme element itself requests another resource. These references should be static resource references, for the reasons mentioned earlier.

The exception behavior if a static resource reference is not found varies. If the resource was deferred, then the exception occurs at runtime. If the resource was not deferred, the exception occurs at load time.

Dynamic Resources

Dynamic resources work best for the following circumstances:

  • The value of the resource depends on conditions that are not known until runtime. This includes system resources, or resources that are otherwise user settable. For example, you can create setter values that refer to system properties, as exposed by SystemColors, SystemFonts, or SystemParameters. These values are truly dynamic because they ultimately come from the runtime environment of the user and operating system. You might also have application-level themes that can change, where page-level resource access must also capture the change.

  • You are creating or referencing theme styles for a custom control.

  • You intend to adjust the contents of a ResourceDictionary during an application lifetime.

  • You have a complicated resource structure that has interdependencies, where a forward reference may be required. Static resource references do not support forward references, but dynamic resource references do support them because the resource does not need to be evaluated until runtime, and forward references are therefore not a relevant concept.

  • You are referencing a resource that is particularly large from the perspective of a compile or working set, and the resource might not be used immediately when the page loads. Static resource references always load from XAML when the page loads; however, a dynamic resource reference does not load until it is actually used.

  • You are creating a style where setter values might come from other values that are influenced by themes or other user settings.

  • You are applying resources to elements that might be reparented in the logical tree during application lifetime. Changing the parent also potentially changes the resource lookup scope, so if you want the resource for a reparented element to be reevaluated based on the new scope, always use a dynamic resource reference.

Dynamic resource lookup behavior

Resource lookup behavior for a dynamic resource reference parallels the lookup behavior in your code if you call FindResource or SetResourceReference.

  1. The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.

  2. The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.

  3. Next, application resources are checked. Application resources are those resources within the resource dictionary that is defined by the Application object for your WPF application.

  4. Theme resource dictionary is checked, for the currently active theme. If the theme changes at runtime, the value is reevaluated.

  5. System resources are checked.

Exception behavior (if any) varies:

  • If a resource was requested by a FindResource call, and was not found, an exception is raised.

  • If a resource was requested by a TryFindResource call, and was not found, no exception is raised, but the returned value is null. If the property being set does not accept null, then it is still possible that a deeper exception will be raised (this depends on the individual property being set).

  • If a resource was requested by a dynamic resource reference in XAML, and was not found, then the behavior depends on the general property system, but the general behavior is as if no property setting operation occurred at the level where the resource exists. For instance, if you attempt to set the background on a an individual button element using a resource that could not be evaluated, then no value set results, but the effective value can still come from other participants in the property system and value precedence. For instance, the background value might still come from a locally defined button style, or from the theme style. For properties that are not defined by theme styles, the effective value after a failed resource evaluation might come from the default value in the property metadata.

Restrictions

Dynamic resource references have some notable restrictions. At least one of the following must be true:

Because the property being set must be a DependencyProperty or Freezable property, most property changes can propagate to UI because a property change (the changed dynamic resource value) is acknowledged by the property system. Most controls include logic that will force another layout of a control if a DependencyProperty changes and that property might affect layout. However, not all properties that have a DynamicResource Markup Extension as their value are guaranteed to provide the value in such a way that they update in realtime in the UI. That functionality still might vary depending on the property, as well as depending on the type that owns the property, or even the logical structure of your application.

Styles, DataTemplates, and Implicit Keys

Earlier, it was stated that all items in a ResourceDictionary must have a key. However, that does not mean that all resources must have an explicit x:Key. Several object types support an implicit key when defined as a resource, where the key value is tied to the value of another property. This is known as an implicit key, whereas an x:Key attribute is an explicit key. You can overwrite any implicit key by specifying an explicit key.

One very important scenario for resources is when you define a Style. In fact, a Style is almost always defined as an entry in a resource dictionary, because styles are inherently intended for reuse. For more information about styles, see Styling and Templating.

Styles for controls can be both created with and referenced with an implicit key. The theme styles that define the default appearance of a control rely on this implicit key. The implicit key from the standpoint of requesting it is the Type of the control itself. The implicit key from the standpoint of defining the resource is the TargetType of the style. Therefore, if you are creating themes for custom controls, creating styles that interact with existing theme styles, you do not need to specify an x:Key Directive for that Style. And if you want to use the themed styles, you do not need to specify any style at all. For instance, the following style definition works, even though the Style resource does not appear to have a key:

<Style TargetType="Button">
  <Setter Property="Background">
    <Setter.Value>
      <LinearGradientBrush>
        <GradientStop Offset="0.0" Color="AliceBlue"/>
        <GradientStop Offset="1.0" Color="Salmon"/>           
      </LinearGradientBrush>
    </Setter.Value>
  </Setter>  
  <Setter Property="FontSize" Value="18"/>
</Style>

That style really does have a key: the implicit key typeof(Button). In markup, you can specify a TargetType directly as the type name (or you can optionally use {x:Type...} to return a Type.

Through the default theme style mechanisms used by WPF, that style is applied as the runtime style of a Button on the page, even though the Button itself does not attempt to specify its Style property or a specific resource reference to the style. Your style defined in the page is found earlier in the lookup sequence earlier than the theme dictionary style, using the same key that the theme dictionary style has. You could just specify <Button>Hello</Button> anywhere in the page, and the style you defined with TargetType of Button would apply to that button. If you want, you can still explicitly key the style with the same type value as TargetType, for clarity in your markup, but that is optional.

Implicit keys for styles do not apply on a control if OverridesDefaultStyle is true (also note that OverridesDefaultStyle might be set as part of native behavior for the control class, rather than explicitly on an instance of the control). Also, in order to support implicit keys for derived class scenarios, the control must override DefaultStyleKey (all existing controls provided as part of WPF do this). For more information about styles, themes, and control design, see Guidelines for Designing Stylable Controls.

DataTemplate also has an implicit key. The implicit key for a DataTemplate is the DataType property value. DataType can also be specified as the name of the type rather than explicitly using {x:Type...}. For details, see Data Templating Overview.

See Also

Tasks

How to: Define and Reference a Resource

Reference

x:Type Markup Extension

ResourceDictionary

StaticResource Markup Extension

DynamicResource Markup Extension

Concepts

Optimizing Performance: Application Resources

Resources and Code

Application Management Overview