Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

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

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:foorunkin
esourcesleaf_styles.xaml", UriKind.Absolute) });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...