In WPF how do I reference a static resource that is defined in a different XAML file? It's in the same project.
In WPF how do I reference a static resource that is defined in a different XAML file?
Asked Answered
The other XAML file will need to be a resource dictionary. You merge it into the current file using the MergedDictionaries property of the current ResourceDictionary. See Merged Resource Dictionaries on MSDN. Their example:
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="myresourcedictionary.xaml"/>
<ResourceDictionary Source="myresourcedictionary2.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
Then within that Page object you can reference static resources defined in myresourcedictionary.xaml
or in myresourcedictionary2.xaml
.
This only really works in the application's resource's merged dictionaries. I created a "Controls" dictionary (containing all the dictionaries containing styles for all my controls) which I added to my application's merged resources, but StaticResources weren't being resolved across style files. But when I removed the middle man (Controls), it works fine. I guess XAML isn't able to scan the hierarchy of merged dictionaries when not processing the application's root dictionary for some reason –
Tusche
"different XAML file" could mean a few different things:
- App.xaml: Resources are automatically included in the resource tree of anything that's opened so you don't need to do anything extra.
- Window or Page .xaml: Resources can be accessed by any child of an instance of the object like a UserControl that is used in a Window.
- ResourceDictionary: Needs to be explicitly merged into the resource tree somewhere above where it is used. This can be App.xaml, Windowxx.xaml, or some lower level element. Use ResourceDictionary.MergedDictionaries to do this.
There are also lots of alternate ways to specify the path but this is the simplest:
<Window>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/MyResourceDict.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
© 2022 - 2024 — McMap. All rights reserved.