如何获取程序集中定义的XAML资源列表?

是否可以枚举程序集中定义的所有XAML资源? 我知道如果有可用的密钥,如何检索资源,但在我的情况下并非如此。

编辑:似乎我不够清楚。 我想列出在我知道完整路径的外部程序集中定义的XAML资源。

是的,你可以通过循环迭代资源。 例如,使用foreach循环:

 foreach (var res in Application.Current.Resources) { Console.WriteLine(res); } 

更新:

要从外部库获取所有ResourceDictionary'ies ,首先应该加载库,然后获取ManifestResourceInfo 。 让我举个例子:

 string address = @"WpfCustomControlLibrary.dll"; List bamlStreams = new List(); Assembly skinAssembly = Assembly.LoadFrom(address); string[] resourceDictionaries = skinAssembly.GetManifestResourceNames(); foreach (string resourceName in resourceDictionaries) { ManifestResourceInfo info = skinAssembly.GetManifestResourceInfo(resourceName); if (info.ResourceLocation != ResourceLocation.ContainedInAnotherAssembly) { Stream resourceStream = skinAssembly.GetManifestResourceStream(resourceName); using (ResourceReader reader = new ResourceReader(resourceStream)) { foreach (DictionaryEntry entry in reader) { //Here you can see all your ResourceDictionaries //entry is your ResourceDictionary from assembly } } } } 

您可以在reader看到所有的ResourceDictionary 。 请看上面的代码。

我已经测试了这段代码,但它确实有效。

试试以下代码:

  ResourceDictionary dictionary = new ResourceDictionary(); dictionary.Source = new Uri("pack://application:,,,/WpfControlAssembly;Component/RD1.xaml", UriKind.Absolute); foreach (var item in dictionary.Values) { //Operations } 

这里WpfControlAssembly是程序集的名称。 Component是固定值,然后RD1.xamlResource Dictionary

以下是输出:

资源字典

资源字典

代码输出:

产量

PS:所有ResourceDictionary文件都应该将Build Action作为'Resource''Page'

更新:

最后我能做到这一点。 请使用以下方法:

 public ResourceDictionary GetResourceDictionary(string assemblyName) { Assembly asm = Assembly.LoadFrom(assemblyName); Stream stream = asm.GetManifestResourceStream(asm.GetName().Name + ".g.resources"); using (ResourceReader reader = new ResourceReader(stream)) { foreach (DictionaryEntry entry in reader) { var readStream = entry.Value as Stream; Baml2006Reader bamlReader = new Baml2006Reader(readStream); var loadedObject = System.Windows.Markup.XamlReader.Load(bamlReader); if (loadedObject is ResourceDictionary) { return loadedObject as ResourceDictionary; } } } return null; } 

OUTPUT:

RD

没有任何try-catch和预期的Exceptions ,我认为在更多WPF(而不是将所有内容转换为ResourceDictionary )的方式。