我可以在代码隐藏中获得样式的关键吗?(WPF)

Mar*_*ter 12 .net wpf styles

如果我有以下代码:

Style defaultStyle = (Style)FindResource("MyTestStyle");
Run Code Online (Sandbox Code Playgroud)

有没有办法得到样式的名称(即反向查找)?就像是:

string name = defaultStyle.SomeMagicLookUpFunction()
Run Code Online (Sandbox Code Playgroud)

名称将评估为"MyTestStyle".

这可能吗?

MrT*_*lly 12

我用一种方法创建了一个小助手类来进行你需要的反向查找.

public static class ResourceHelper
{
    static public string FindNameFromResource(ResourceDictionary dictionary, object resourceItem)
    {
        foreach (object key in dictionary.Keys)
        {
            if (dictionary[key] == resourceItem)
            {
                return key.ToString();
            }
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以使用以下方法调用它

string name = ResourceHelper.FindNameFromResource(this.Resources, defaultStyle);
Run Code Online (Sandbox Code Playgroud)

每个人FrameworkElement都有它自己的.Resources字典,使用'this'假设你在MyTestStyle定义的地方.如果需要,您可以向静态类添加更多方法,以递归方式遍历窗口中的所有字典(应用程序?)