跨项目/ dll访问Xaml中的资源

时间:2009-10-30 20:40:37

标签: wpf xaml resources

是否可以从另一个项目中引用存储在ResourceDictionary(构建操作=资源)中的Xaml资产?我想将资产合并到主项目的资源字典中,或者单独访问它们。例如:

  • 项目“MyResources”包含一个名为“Assets”的文件夹,其中有一个名为“MyAssets.xaml”的ResourceDictionary,其中包含一个名为“ButtonStyle”的样式
  • 项目“MainProject”引用MyResources;在MainWindow.xaml

在MainWindow.xaml中,我想做类似的事情:

<ResourceDictionary.MergedResources>
    <ResourceDictionary Source="/MyResources/Assets/MyAssets.xaml"/>
</ResourceDictionary.MergedResources>

或者,如果那不可能,或许:

<Button Style="{StaticResource /MyResources/Assets/MyAssets.xaml}"/>

有没有办法从MainProject引用MyResources中的东西?

3 个答案:

答案 0 :(得分:14)

根据 ResourceDictionary in a separate assembly

<ResourceDictionary.MergedResources>
  <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
</ResourceDictionary.MergedResources>

答案 1 :(得分:13)

<ResourceDictionary Source="/Commons;component/Themes/TreeStyle.xaml" />

其中:

Commons 是外部项目的名称

/Themes/TreeStyle.xaml 对应项目Commons中样式文件的位置

总是需要

;组件

答案 2 :(得分:4)

您可以使用以下方法将项目中的资源合并到主词典中:

/// <summary>
/// Loads a resource dictionary from a URI and merges it into the application resources.
/// </summary>
/// <param name="resourceLocater">URI of resource dictionary</param>
public static void MergeResourceDictionary(Uri resourceLocater)
{
    if (Application.Current != null)
    {
        var dictionary = (ResourceDictionary) Application.LoadComponent(resourceLocater);
        Application.Current.Resources.MergedDictionaries.Add(dictionary);
    }
}

这样称呼:

MergeResourceDictionary(new Uri(@"/MyOtherAssembly;component/MyOtherResourceDictionary.xaml", UriKind.Relative));                                                           
相关问题