ResourceDictionary 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.
Defines a repository for XAML resources, such as styles, that your app uses. You define the resources in XAML and can then retrieve them in XAML using the {StaticResource} markup extension and {ThemeResource} markup extension. You can also access resources with code, but that is less common.
/// [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 ResourceDictionary : DependencyObject, IIterable<IKeyValuePair<IInspectable, IInspectable const&>>, IMap<IInspectable, IInspectable const&>
[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 ResourceDictionary : DependencyObject, IDictionary<object,object>, IEnumerable<KeyValuePair<object,object>>
Public Class ResourceDictionary
Inherits DependencyObject
Implements IDictionary(Of Object, Object), IEnumerable(Of KeyValuePair(Of Object, Object))
<ResourceDictionary>
oneOrMoreResources
</ResourceDictionary>
- or -
<frameworkElement>
<frameworkElement.Resources>
oneOrMoreResources
</frameworkElement.Resources>
</frameworkElement>
- Inheritance
- Derived
- Attributes
- Implements
-
IDictionary<Object,Object> IMap<IInspectable,IInspectable> IIterable<IKeyValuePair<K,V>> IEnumerable<KeyValuePair<K,V>> IEnumerable<KeyValuePair<Object,Object>> IIterable<IKeyValuePair<IInspectable,IInspectable>>
Remarks
A resource dictionary is a repository for XAML resources, such as styles, that your app uses. You define the resources in XAML and can then retrieve them in XAML using the {StaticResource} markup extension and {ThemeResource} markup extension. You can also access resources with code, but that is less common. You can use resources to enforce that certain values such as brush colors or pixel measurements are used consistently throughout your app. For more info on using resource dictionaries effectively, see ResourceDictionary and XAML resource references.
Uses of ResourceDictionary elements
The ResourceDictionary
type is used as the value of two properties, FrameworkElement.Resources and Application.Resources, that are important to the overall structure of a Windows App SDK app. XAML files that you get from a starting project template for an app will start with initial values for FrameworkElement.Resources, and the app.xaml file might start with initial values for Application.Resources. Exactly what resources are defined there depends on which project starting template you're using.
This XAML shows the use of a FrameworkElement.Resources property. In this case the FrameworkElement is a Page. There is no ResourceDictionary
element subordinate to the Page.Resources
property element, but its presence is implied; for more info see the "Notes on XAML syntax" section below. The XAML places a Style into the ResourceDictionary
with an x:Key attribute value of "TextBlockStyle1". Further down in the XAML, the {StaticResource} markup extension references the Style
in the resource dictionary to provide a value for the Style property of the TextBlock element.
The Style as shown does not actually apply any styling to the TextBlock, but you can add Style
properties in Microsoft Visual Studio. You can then use the Style
resource as often as you like on the page to enforce uniformity.
<Page
x:Class="ResourceDictionary_example.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ResourceDictionary_example"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<Style x:Key="TextBlockStyle1" TargetType="TextBlock"/>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Style="{StaticResource TextBlockStyle1}" Text="TextBlock"/>
</Grid>
</Page>
This XAML, from the AppPage.xaml file of the AtomPub sample, shows the use of an Application.Resources property. The XAML places two Style elements into the resource dictionary, making them available throughout the application.
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="AtomPub.App"
RequestedTheme="Light" >
<Application.Resources>
<ResourceDictionary>
<Style x:Key="TitleStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="#707070"/>
<Setter Property="FontFamily" Value="Segoe UI Light"/>
<Setter Property="FontSize" Value="16"/>
</Style>
<Style x:Key="H1Style" TargetType="TextBlock">
<Setter Property="Foreground" Value="#212121"/>
<Setter Property="FontFamily" Value="Segoe UI Semilight"/>
<Setter Property="FontSize" Value="26.667"/>
<Setter Property="Margin" Value="0,0,0,25"/>
</Style>
...
</ResourceDictionary>
</Application.Resources>
</Application>
This XAML from file MainPage.xaml uses the {StaticResource} markup extension to access the TitleStyle and H1Style styles:
...
<!-- Header -->
<StackPanel x:Name="Header" Grid.Row="0">
<StackPanel Orientation="Horizontal">
...
<TextBlock Text="Windows SDK Samples" VerticalAlignment="Bottom" Style="{StaticResource TitleStyle}" TextWrapping="Wrap"/>
</StackPanel>
<TextBlock x:Name="FeatureName" Text="Add Feature Name" Style="{StaticResource H1Style}" TextWrapping="Wrap"/>
</StackPanel>
...
You can factor resources into their own XAML file by using ResourceDictionary as the root element of the file. You can then include those resources in a FrameworkElement.Resources or Application.Resources resource dictionary. To do this you use the ResourceDictionary.MergedDictionaries property or the ResourceDictionary.ThemeDictionaries property of the ResourceDictionary element.
This file, Common/Styles1.xaml, defines Style resources using ResourceDictionary
as the root element:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="TitleTextStyle" TargetType="TextBlock">
<Setter Property="FontFamily" Value="Segoe UI Light"/>
<Setter Property="FontSize" Value="16"/>
</Style>
<Style x:Key="HeaderTextStyle" TargetType="TextBlock">
<Setter Property="FontFamily" Value="Segoe UI Semilight"/>
<Setter Property="FontSize" Value="26.667"/>
<Setter Property="Margin" Value="0,0,0,25"/>
</Style>
...
</ResourceDictionary>
Now suppose there is another file, Common/Styles2.xaml that similarly defines Style resources. This XAML shows how to merge the resources in those two files using the ResourceDictionary.MergedDictionaries property to create an Application.Resources resource dictionary. The XAML also defines two further Style resources and merges them with the resources from the two files.
<Application
.... >
<Application.Resources>
<ResourceDictionary>
<Style x:Key="ErrorStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="DarkRed"/>
<Setter Property="FontFamily" Value="Segoe UI Semilight"/>
<Setter Property="FontSize" Value="15"/>
</Style>
<Style x:Key="StatusStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontFamily" Value="Segoe UI Semilight"/>
<Setter Property="FontSize" Value="15"/>
</Style>
<ResourceDictionary.MergedDictionaries>
<!--
Styles that define common aspects of the platform look and feel
-->
<ResourceDictionary Source="Common/Styles1.xaml"/>
<ResourceDictionary Source="Common/Styles2.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
For info on how merged dictionary resources are resolved, see the "Merged resource dictionaries" section of ResourceDictionary and XAML resource references.
The x:Key property
In XAML, the keys for ResourceDictionary
items are declared by setting the x:Key attributeon elements that represent the XAML resources. Typically, if you try to put a child element that does not have a key value into a ResourceDictionary
, this throws a XAML parse exception or a Windows Runtime exception. The exception condition might also be noted as a warning by XAML design surfaces. However, there are three notable cases where a ResourceDictionary
child element won't require an x:Key attribute value:
- A Style resource can use its TargetType value as the implicit resource key. For more info on how implicit keys for styles and control templates work, see Styling controls.
- The
ResourceDictionary
elements with Source values that represent ResourceDictionary.MergedDictionaries values can't have an x:Key attribute onResourceDictionary
. Within each merged dictionary file, (the one referenced by URI as its Source) you do need keys for each resource. - The x:Name attribute can be used instead of x:Key attribute, for legacy reasons. However, x:Name attribute by itself doesn't enable XAML resource lookup of that item. The x:Name attribute identifying convention is used for certain scenarios such as defining storyboarded animations. For more info, see x:Name attribute.
Iterating through a ResourceDictionary
You can iterate through a ResourceDictionary
in C#. In many cases, such as using foreach
syntax, the compiler does this casting for you and you won't need to cast to IEnumerable
explicitly. If you do need to cast explicitly, for example if you want to call GetEnumerator, cast to IEnumerable with a KeyValuePair<Object,Object>
constraint.
ResourceDictionary and Microsoft Visual Studio
Microsoft Visual Studio provides an Add New Item page choice for a resource dictionary. Use this option whenever you want to define a new loose XAML resource dictionary, for example to serve as the source for a merged dictionary. Microsoft Visual Studio also adds a loose XAML resource dictionary to the project whenever you use Add New Item to create a templated control. This resource dictionary provides the default theme templates. Microsoft Visual Studio might create a new ResourceDictionary
for you in your XAML if you are editing copies of styles or templates and a ResourceDictionary
for your chosen resource location (app, page, or standalone) doesn't exist yet.
Notes on XAML syntax
Notice that the XAML implicit collection syntax for ResourceDictionary
does not include an object element for the ResourceDictionary
. This is an example of XAML implicit collection syntax; a tag representing the collection element can be omitted. The elements that are added as items to the collection are specified as child elements of a property element of a property whose underlying type supports a dictionary / map Add method.
For a merged resource dictionary, you do need to explicitly declare a ResourceDictionary
object element, so that you can also declare the ResourceDictionary.MergedDictionaries property element and Source. Thus there are a minimum of two ResourceDictionary
object elements involved, and you use this syntax.
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="uri"/>
...
</ResourceDictionary.MergedDictionaries>
...
</ResourceDictionary>
In this syntax the outer ResourceDictionary
is the primary ResourceDictionary
. The inner ResourceDictionary
is the ResourceDictionary
being merged.
For the implicit collection usage, the placeholder as appropriate for the property FrameworkElement.Resources is shown. You could also use this implicit collection usage for the Application.Resources property, or potentially for a custom property that uses ResourceDictionary
as its property type.
Shareable types and UIElement types
A resource dictionary is a technique for defining shareable types and values of these types in XAML. Not all types or values are suitable for usage from a ResourceDictionary
. Examples of types where sharing is supported include Style, any FrameworkTemplate subclass, the XAML intrinsic data types, brushes, colors, and transforms. For more info on which types are considered shareable, see ResourceDictionary and XAML resource references. Generally, UIElement-derived types are not shareable unless they come from templates and application of a template on a specific control instance. Excluding the template case, a UIElement is expected to exist in only one place in an object tree after it is instantiated, and having a UIElement be shareable would potentially violate this principle.
In practice, the vast majority of the resources defined in a ResourceDictionary
will be one of these:
- Control templates for a control, including its visual states.
- Supporting styles for parts of controls
- Styles for elements that are part of typical app UI but aren't controls, like TextBlock
- Data templates for controls and panels that use data binding
- Specific Brush values, mostly SolidColorBrush
- Strings or other constants that never need to be localized (strings and constants that do need to be localized shouldn't be in a ResourceDictionary; for more info see Quickstart: Translating UI resources)
Accessing a ResourceDictionary object in code
The API that your code uses to access the resources in a ResourceDictionary depends on which programming language you use:
- For C# you use API that implement IDictionary<TKey,TValue> and IEnumerable. For example, TryGetValue or the Item indexer.
- API that aren't part of collection support, like Source, are the same in all languages.
For more info on how to use ResourceDictionary
in code, see "Using a ResourceDictionary from code" section of ResourceDictionary and XAML resource references.
System resources
Some theme resources reference system resource values as an underlying sub-value. A system resource is a special resource value that isn't found in any XAML resource dictionary. These values rely on behavior in Windows Runtime XAML support to forward values from the system itself, and represent them in a form that a XAML resource can reference.
Constructors
ResourceDictionary() |
Initializes a new instance of the ResourceDictionary class. |
Properties
Dispatcher |
Always returns |
DispatcherQueue |
Gets the |
MergedDictionaries |
Gets a collection of the ResourceDictionary dictionaries that constitute the various resource dictionaries in the merged dictionaries. |
Size |
Gets the number of elements contained in the collection. |
Source |
Gets or sets a Uniform Resource Identifier (URI) that provides the source location of a merged resource dictionary. |
ThemeDictionaries |
Gets a collection of merged resource dictionaries that are specifically keyed and composed to address theme scenarios, for example supplying theme values for "HighContrast". |
Methods
Clear() |
Removes all items from this ResourceDictionary. |
ClearValue(DependencyProperty) |
Clears the local value of a dependency property. (Inherited from DependencyObject) |
First() |
Returns an iterator for the items in the collection. |
GetAnimationBaseValue(DependencyProperty) |
Returns any base value established for a dependency property, which would apply in cases where an animation is not active. (Inherited from DependencyObject) |
GetValue(DependencyProperty) |
Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) |
GetView() |
Retrieves a view against the ResourceDictionary. |
HasKey(Object) |
Returns whether the ResourceDictionary has an entry with the requested key. |
Insert(Object, Object) |
Adds a new entry to the ResourceDictionary. |
Lookup(Object) |
Returns the value from the requested key, if an entry with that key exists. |
ReadLocalValue(DependencyProperty) |
Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject) |
RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback) |
Registers a notification function for listening to changes to a specific DependencyProperty on this DependencyObject instance. (Inherited from DependencyObject) |
Remove(Object) |
Removes a specific item from the ResourceDictionary. |
SetValue(DependencyProperty, Object) |
Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) |
UnregisterPropertyChangedCallback(DependencyProperty, Int64) |
Cancels a change notification that was previously registered by calling RegisterPropertyChangedCallback. (Inherited from DependencyObject) |