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

ion*_*noy 5 c# wpf xaml

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

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

Ste*_*pUp 7

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

foreach (var res in Application.Current.Resources)
{
     Console.WriteLine(res);
}
Run Code Online (Sandbox Code Playgroud)

更新:

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

string address = @"WpfCustomControlLibrary.dll";
List<Stream> bamlStreams = new List<Stream>();
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
          }
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以看到你所有的ResourceDictionary"S IN reader.请参阅上面的代码.

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


Kyl*_*Ren 7

试试以下代码:

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

WpfControlAssembly是你的程序集的名称.Component是固定值,然后RD1.xaml是一个Resource 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;
    }
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

RD

没有任何尝试捕获和预期Exceptions,我认为在更多的WPF(而不是转换一切ResourceDictionary)的方式.