In WPF, how do I refer to a static resource defined in another XAML file?

In WPF, how do I refer to a static resource defined in another XAML file? This is in the same project.

+7
c # wpf xaml staticresource
source share
2 answers

The other XAML file should be a resource dictionary. You merge it into the current file using the MergedDictionaries property of the current ResourceDictionary. See Combined 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, inside this page object, you can refer to static resources defined in myresourcedictionary.xaml or in myresourcedictionary2.xaml .

+8
source share

โ€œanother XAML fileโ€ can mean several different things:

  • App.xaml: resources are automatically included in the resource tree of everything that was open, so you do not need to do anything.
  • Window or .xaml page: access to resources can be obtained by any child of an instance of an object, such as UserControl, which is used in a window.
  • ResourceDictionary: must be explicitly merged into a resource tree somewhere above where it is used. It can be App.xaml, Windowxx.xaml or some element of a lower level. Use ResourceDictionary.MergedDictionaries for this.

There are also many alternative ways to indicate the path, but this is the simplest:

 <Window> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/MyResourceDict.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources> 
+3
source share

All Articles