Accessing resources in Xaml across projects/dlls

2019-03-13 20:24发布

Is it possible to reference Xaml assets stored in a ResourceDictionary (build action = resource) from another project? I would like to either merge the assets into the main project's resource dictionary or access them individual. For example:

  • Project "MyResources" contains a folder named "Assets" which has a ResourceDictionary called "MyAssets.xaml" which contains a Style called "ButtonStyle"
  • Project "MainProject" references MyResources; in MainWindow.xaml

In MainWindow.xaml I'd like to do something like:

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

Or, if that's not possible, perhaps:

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

Is there a way to refer to stuff in MyResources from MainProject?

3条回答
我命由我不由天
2楼-- · 2019-03-13 20:35

According to ResourceDictionary in a separate assembly

<ResourceDictionary.MergedResources>
  <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
</ResourceDictionary.MergedResources>
查看更多
ゆ 、 Hurt°
3楼-- · 2019-03-13 20:39

You can merge the resources from your project into your main dictionary using this method:

/// <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);
    }
}

Call it like this:

MergeResourceDictionary(new Uri(@"/MyOtherAssembly;component/MyOtherResourceDictionary.xaml", UriKind.Relative));                                                           
查看更多
趁早两清
4楼-- · 2019-03-13 20:41
<ResourceDictionary Source="/Commons;component/Themes/TreeStyle.xaml" />

Where:

Commons is the name of the external project

/Themes/TreeStyle.xaml corresponds to the location of the style file in project Commons

;component is always required

查看更多
登录 后发表回答