How to: Use an Application-Scope Resource Dictionary

 

This example shows how to define and use an application-scope custom resource dictionary.

Example

Application exposes an application-scope store for shared resources: Resources. By default, the Resources property is initialized with an instance of the ResourceDictionary type. You use this instance when you get and set application-scope properties using Resources. (For more information, see How to: Get and Set an Application-Scope Resource.)

If you have multiple resources that you set using Resources, you can instead use a custom resource dictionary to store those resources and set Resources with it instead. The following shows how you declare a custom resource dictionary using XAML .

<ResourceDictionary 
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
	<SolidColorBrush x:Key="StandardSolidColorBrush" Color="Blue" />
	<LinearGradientBrush x:Key="StandardLinearGradientBrush" StartPoint="0.0,0.0" EndPoint="1.0,1.0">
		<LinearGradientBrush.GradientStops>
			<GradientStop Color="White" Offset="0" />
			<GradientStop Color="Black" Offset="1" />
		</LinearGradientBrush.GradientStops>
	</LinearGradientBrush>
</ResourceDictionary>

Swapping entire resource dictionaries using Resources allows you to support application-scope themes, where each theme is encapsulated by a single resource dictionary. The following example shows how to set the ResourceDictionary.

<!--Set the Application ResourceDictionary-->
<Application.Resources>
    <ResourceDictionary Source="MyResourceDictionary.xaml" />
</Application.Resources>

The following shows how you can get application-scope resources from the resource dictionary exposed by Resources in XAML.

<!--Set the brush as a StaticResource from the ResourceDictionary-->
<Rectangle Name="Rect" Height="200" Width="100" Fill="{StaticResource ResourceKey=StandardSolidColorBrush}" />

The following shows how you can also get the resources in code.

'Get a resource from the ResourceDictionary in code
Dim GradientBrush As Brush = Application.Current.FindResource("StandardLinearGradientBrush")

There are two considerations to make when using Resources. First, the dictionary key is an object, so you must use exactly the same object instance when both setting and getting a property value. (Note that the key is case-sensitive when using a string.) Second, the dictionary value is an object, so you will have to convert the value to the desired type when getting a property value.

Show: