Condividi tramite


How to: Get and Set Application-Scope Resources

This example shows how to both get and set application-scope resources using Resources.

Example

Application exposes an application-scope store for shared resources: Resources. Resources stored in Resources are available from any code that executes within the scope of an application's Application object (ie code that can access Current). Furthermore, Resources is used in the resource lookup path.

Resources is a dictionary of key/value pairs that you can set from both markup and code, like so:

// Set an application-scope resource
Application.Current.Resources["ApplicationScopeResource"] = Brushes.White;
<Application.Resources>
    <SolidColorBrush x:Key="ApplicationScopeResource" Color="White"></SolidColorBrush>
</Application.Resources>

You use code to get a resource:

// Get an application-scope resource
Brush whiteBrush = (Brush)Application.Current.Resources["ApplicationScopeResource"];

There are two considerations to make when using Resources. First, the dictionary key is an object, so you need to 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 need to convert the value to the desired type when getting a property value.

See Also

Reference

ResourceDictionary