WPF C# Reflection: Iterate over all resources with build action “Page”

孤者浪人 提交于 2019-12-13 22:18:20

问题


I have a .dll with a lot of ResourceDictionaries.

The build action of all these ResourceDictionaries is set to "Page".

Inside the Dll, I want to find all these ResourceDictionaries and iterate over them.

If I set the build action to "EmbeddedResource", I can use Reflection:

var embeddedResources = Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList();

But GetManifestResourceNames() does not work for resources with build action "Page".

How do I find or iterate over all resources that have the build action "page"?

The solution doesn't have to be Reflection. Any other way is very welcome.

Thank you!

Solution:

Ladies and Gentleman! I have to announce, that the man of the week and the winner of this bounty, is Mr. Jon Wu. Jon Wu gave the right hint and through searching, I found this solution:

Enumerating .NET assembly resources at runtime

The working code, slightly changed looks like this:

public static string[] GetResourceNames()
    {
        var asm = Assembly.GetExecutingAssembly();
        string resName = asm.GetName().Name + ".g.resources";
        using (var stream = asm.GetManifestResourceStream(resName))
        using (var reader = new System.Resources.ResourceReader(stream))
        {
            return reader.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).ToArray();
        }
    }

If you call this method, you get all the resource strings with a ".baml" at the end and you can iterate over them.

Thank you Jon Wu for the right hint.


回答1:


According to this answer,

Page (WPF only): Used to compile a xaml file into baml. The baml is then embedded with the same technique as Resource (i.e. available as AppName.g.resources).

So it sounds like you just need to look for resources identified with YourAppName.g.resources.



来源:https://stackoverflow.com/questions/44663908/wpf-c-sharp-reflection-iterate-over-all-resources-with-build-action-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!