views:

379

answers:

2

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?

+2  A: 

According to http://stackoverflow.com/questions/338056/wpf-resource-dictionary-in-a-separate-assembly

<ResourceDictionary.MergedResources>
  <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
</ResourceDictionary.MergedResources>
Lars Truijens
Thank you, my search should have turned that up. This is a dupe.
James Cadd
A: 

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));
GraemeF
Thanks for providing a code based answer as well, if I could have marked a second answer I would have!
James Cadd