I have a WPF application which I would like to use some static resources in. I have created a Resource Library XAML file which contains a resource. I have also added a string into the Resources of the project through the Properties panel.
I assumed I could just use these resources with the binding expression:
{StaticResource ResourceName}
But visual studio is telling me the resources are not found. Do I have to include some form of reference in my XAML? The examples I have seen only include resources locally such as:
<Window.Resources>, <Page.Resources> etc
I don't want to include the resources locally because I want them to be available to multiple parts of the application.
To add a Resource Dictionary into your WPF application, right click the WPF project > add a Resource Dictionary. Now apply the resource "myAnotherBackgroundColor" to button background and observe the changes.
WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles. Resource data files are non-executable data files that an application needs.
You can reference a resource throughout an app or from any XAML page within it. You can define your resources using a ResourceDictionary element from the Windows Runtime XAML. Then, you can reference your resources by using a StaticResource markup extension or ThemeResource markup extension.
Put them in the App.xaml :)
In each WPF application there is an App.xaml (and its corresponding code file, App.xaml.cs or App.xaml.vb) which works as a global file for application wide declarations. You can use this file to declare a constant look and feel across your application. For example you can declare a default red background for all buttons in an application.
http://www.microsoft.com/emea/msdn/thepanel/en/articles/introduction_wpf.aspx
You can create a dictionary of global resources and include its path in app.xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/YourProject;Component/YourXamlFile.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Now all your resources in the YourXamlFile.xaml will be visible globally in your project.
Look at the section on "static resource lookup behavior" here. Anything in the application's resource dictionary (i.e. Application.Resources
) is available globally. Whenever you look up a resource with a given key, and the key isn't used anywhere in the hierarchy of local resource dictionaries, the one in the application's dictionary will be returned.
To populate the application's resource dictionary in XAML, find the XAML file for the application (usually App.xaml) and add an Application.Resources
element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With