我能得到一个风格的关键在code-后面? (WPF) [英] Can i get the key of a style in code-behind? (WPF)

查看:171
本文介绍了我能得到一个风格的关键在code-后面? (WPF)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下的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 ?)

这篇关于我能得到一个风格的关键在code-后面? (WPF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆