C# 从程序集中加载 ResourceDictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/709087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 14:17:19  来源:igfitidea点击:

Load a ResourceDictionary from an assembly

c#wpfxamlresourcedictionary

提问by Christian Hubmann

I've got an assembly somewhere on the file system, e.g. "C:\temp\test.dll". In that assembly there's a ResourceDictionary, e.g. "abc.xaml".

我在文件系统的某个地方有一个程序集,例如“C:\temp\test.dll”。在那个程序集中有一个ResourceDictionary,例如“abc.xaml”。

How can i get that ResourceDictionary? Maybe there is a way using Reflections? I didn't find a solution so far.

我怎样才能得到那个ResourceDictionary?也许有一种使用反射的方法?到目前为止我没有找到解决方案。

Thanks in advance!

提前致谢!

Edit: Just wanted to add that I want to access the Resources in the Dictionary, e.g. a Style.

编辑:只是想补充一点,我想访问词典中的资源,例如样式。

采纳答案by Christian Hubmann

Edit:I found an even better solution which works with ResourceDictionaries:

编辑:我找到了一个更好的解决方案,它适用于 ResourceDictionaries:

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


Well, I couldn't get it to work with ResourceDictionaries, so I'm using good old Resource Files instead ;) For anyone interested, here is how I did it:

好吧,我无法让它与 ResourceDictionaries 一起工作,所以我使用的是旧的资源文件;) 对于任何感兴趣的人,我是这样做的:

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

You can get "NameOfResource" with Reflector, as Ian suggested.

正如 Ian 建议的那样,您可以使用 Reflector 获得“NameOfResource”。

回答by Dead account

Grab a copy of Reflector(Lutz has handed this over now). Use that to look at the assembly and the namespace etc of the resources in it.

拿一份反射器(Lutz 现在已经把它交给了)。使用它来查看程序集和其中资源的命名空间等。

Then read in the embedded resource something like this;

然后在嵌入的资源中读取这样的内容;

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

回答by Christian Hubmann

You actually need to write the Uri like this:

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

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