.net - 我可以在代码隐藏中获取样式的键吗? (WPF)

标签 .net wpf styles

如果我有以下代码:

Style defaultStyle = (Style)FindResource("MyTestStyle");

有没有办法获得样式的名称(即反向查找)?类似的东西:
string name = defaultStyle.SomeMagicLookUpFunction()

其中 name 将评估为“MyTestStyle”。

这可能吗?

最佳答案

我创建了一个小的帮助器类,它使用一个方法来执行您需要的反向查找。

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

您可以使用以下方法调用它
string name = ResourceHelper.FindNameFromResource(this.Resources, defaultStyle);

FrameworkElement有自己的.Resources字典,使用 'this' 假定您处于定义 MyTestStyle 的正确位置。如果需要,您可以向静态类添加更多方法以递归遍历窗口中的所有字典(应用程序?)

关于.net - 我可以在代码隐藏中获取样式的键吗? (WPF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/538750/

相关文章:

.net - 对象捕获自己的异常并将消息存储在属性中是不好的做法吗?

c# - GDI+ 就像在 WPF 中绘图一样

c# - 在 App.xaml 中访问 Controltemplate 中的 Textblock,在 App.xaml.cs 中

c# - 如何在 wpf 中的文本绑定(bind)前面添加项目符号?

html - IE相当于-webkit-appearance?

Javascript下拉更改样式显示不起作用

jquery - Bootstrap Datepicker - 自定义样式

c# - 在 .NET 中使进程窗口可见/不可见

c# - 我可以将 libxml2 导入 Visual Studio 2013

c# - C# 中的固定语句