我能得到一个风格的关键在code-后面? (WPF)我能、后面、风格、关键

2023-09-03 01:55:21 作者:风清淡雅

如果我有以下的code:

If I have the following code:

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

有没有一种方法来获取样式的名称(即反向查找)?是这样的:

Is there a way to get the name of the style (i.e. reverse-lookup)? Something like:

string name = defaultStyle.SomeMagicLookUpFunction()

其中name将评估为MyTestStyle。

Where name would evaluate to "MyTestStyle."

这可能吗?

推荐答案

我创建了一个小助手类有一个方法来做到这一点,你需要反向查找。

I've created a small helper class with a single method to do the reverse lookup that you require.

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 词典,用这个假设你是在正确的地方对于其中MyTestStyle定义。如果需要的话,你可以添加更多的方法,以静态类递归遍历在一个窗口中的所有词典(应用程序?)

Every FrameworkElement has it's own .Resources dictionary, using 'this' assumes you're in the right place for where MyTestStyle is defined. If needs be you could add more methods to the static class to recursively traverse all the dictionaries in a window (application ?)