从程序集中加载 ResourceDictionary

16

我在文件系统上的某个地方有一个程序集,例如 "C:\temp\test.dll"。

在这个程序集中有一个 ResourceDictionary,例如 "abc.xaml"。

如何获取该 ResourceDictionary?也许可以使用 Reflections 的方法吗?目前我还没有找到解决方法。

先谢谢您了!

编辑:补充说明我想要访问字典中的资源,例如一个样式。

3个回答

20

你实际上需要像这样编写Uri:

Assembly.LoadFrom(@"C:\temp\test.dll");
ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri(@"pack://application:,,,/test;component/myresource.xaml");

5
滑稽的Uri语法文档在这里: http://msdn.microsoft.com/zh-cn/library/aa970069.aspx(说明:以上翻译为简洁化处理,如需更严谨的翻译请提供更多上下文信息) - scobi

9

编辑:我找到了一种更好的解决方案,它可以与资源字典一起使用:

Assembly.LoadFrom(@"C:\temp\test.dll");
ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri("/test;component/myresource.xaml");

我无法让ResourceDictionaries正常工作,所以我改用传统的资源文件;)

对于任何有兴趣的人,这是我做的:

Assembly a = Assembly.LoadFile(@"C:\temp\test.dll");
ResourceManager rm = new ResourceManager("NameOfResource", a);
object o = rm.GetObject("xyz");

如Ian所建议的,您可以使用Reflector获取“NameOfResource”。

3
回来告诉我们你如何解决问题总是很好的,:+1: - Dead account
看Claraoscura的回答,那是一个更好的解决方案。 - scobi
你的回答中缺少了 UriKind,如果你使用相对路径,应该提供 UriKind.Relative - ANewGuyInTown

2
请使用Reflector(Lutz现在已经移交)获取副本。使用它查看程序集和其中资源的名称空间等信息。然后像这样读取嵌入式资源;
Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
using (System.IO.Stream s = asm.GetManifestResourceStream(<yourname>)
{
    using (System.IO.StreamReader reader = new System.IO.StreamReader(s))
    {
        string xml = reader.ReadToEnd();
    }
}

谢谢。不幸的是,当我使用您的代码时,我只是从reader.ReadToEnd()得到垃圾。 - Christian Hubmann
我不知道XAML是什么样子的,但我猜你需要某种解码器? - Dead account
我不知道,但是现在我用资源文件做到了。感谢你的帮助! - Christian Hubmann
@christian - 垃圾是BAML而不是XAML:http://blogs.microsoft.co.il/blogs/tomershamam/archive/2007/05/25/Compiled-XAML-_3D00_-BAML-not-IL.aspx - Simon_Weaver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接