Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing resources in Xaml across projects/dlls

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?

like image 720
James Cadd Avatar asked Oct 30 '09 20:10

James Cadd


3 Answers

According to ResourceDictionary in a separate assembly

<ResourceDictionary.MergedResources>
  <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
</ResourceDictionary.MergedResources>
like image 121
Lars Truijens Avatar answered Oct 30 '22 03:10

Lars Truijens


<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

like image 28
tsunllly Avatar answered Oct 30 '22 04:10

tsunllly


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));                                                           
like image 34
GraemeF Avatar answered Oct 30 '22 02:10

GraemeF