开发者

In WPF how do I reference a static resource that is defined in a different XAML file?

In WPF how d开发者_开发问答o I reference a static resource that is defined in a different XAML file? It's in the same project.


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.


"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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜