views:

36

answers:

2

In WPF how do I reference a static resource that is defined in a different XAML file? It's in the same project.

+2  A: 

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.

Quartermeister
+1  A: 

"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>
John Bowen