Dynamically loading resource dictionary files to a wpf application gives an error

sudarsanyes picture sudarsanyes · May 17, 2011 · Viewed 34.3k times · Source

I am trying to add a xaml resource file dynamically using the statement,

Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("resources/leaf_styles.xaml", UriKind.Relative) });

This is throwing an exception, Cannot locate resource 'resources/leaf_styles.xaml'.

I added the leaf_styles.xaml file to the project under resource folder and the BuildAction is set to "Content", CopyAlways is set to True. Still I get this error. Could some one help me out pointing whats wrong??

Additional information -

  • I don't want to embed the xaml file as a resource
  • The current project is a .net 3.5 class library project
  • The above mergedictionary statement is written in a class belonging to the same project
  • I also added the [assembly: AssemblyAssociatedContentFile("resources/leaf_styles.xaml")] manually once I figured that this is not working (for testing)

Update

If I give it as an absolute location, it is working properly.

Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(@"D:\foo\trunk\bin\resources\leaf_styles.xaml", UriKind.Absolute) });

Answer

sudarsanyes picture sudarsanyes · May 18, 2011

At last, it worked. Here is what I did,

  1. Went thru' http://msdn.microsoft.com/en-us/library/aa970069.aspx.
  2. Changed the Uri pattern to

    var foo = new Uri("pack://siteoforigin:,,,/resources/leaf_styles.xaml", UriKind.RelativeOrAbsolute);
    Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = foo });