0

I need to load my ResourceDictionary from some assemblies at runtime.

First i set BuildAction of the ResourceDictionary with Page, and use the code to build the uri.

    var uri = new Uri(string.Format(@"/{0};component\Resources\MyResource.xaml",
 assemblyName), UriKind.RelativeOrAbsolute);

That works, but then i realized that, i need to check the assembly, before i set the uri to my ResourceDictionary. Because, if the ResourceDictionary is not in the assembly, that will throw a exception.

var rd = new ResourceDictionary
         {
             Source = uri
         };

So i set the BuildAction of my ResourceDictionary with EmbeddedResource, in order to see the ResourceDictionary in the assembly with the code below:

var hasResource = assembly.GetManifestResourceNames().
                 Any(resourceName => resourceName.EndsWith("MyResource.xaml"));

But now, i can't load the ResourceDictionary with the uri. I have tried all i can, but no success.

Any idea? Thanks!

Ivan
  • 81
  • 2
  • 11

1 Answers1

2

Try setting the Build Action to Page and then you can access the assemblys Resource like this:

ResourceDictionary resources = new ResourceDictionary();
resources.Source = new Uri("pack://application:,,,/AssemblyName;component\Resources\MyResource.xaml");

Then you can access the resources like this:

object obj = resources["key"];
Miro Bucko
  • 1,123
  • 1
  • 13
  • 26
  • That is almost like my code. That will also throw exception, if the MyResource.xaml is not in the assembly. – Ivan Mar 13 '14 at 08:15
  • You're right, i have completely overlooked your assemblyName variable. How ever have you tried setting the build action to Page? – Miro Bucko Mar 13 '14 at 08:42
  • It seems, that you overlooked not any my assemblyName variable ;- ) Yes, i have tried that at beginning. My problem is not to access the resources from Page. It is about to set Uri to Source of ResourceDictionary. There comes the exception, if Resource.xaml is not in assembly. – Ivan Mar 13 '14 at 08:47
  • Are you trying to find out how to check if the resource is included in the assembly? – Miro Bucko Mar 13 '14 at 09:00
  • Yes, something like that. – Ivan Mar 13 '14 at 09:02
  • What about catching the exception? – Miro Bucko Mar 13 '14 at 10:37
  • Catching the exception is the last solution... if i really find no any other. – Ivan Mar 13 '14 at 12:26