Can i get the key of a style in code-behind? (WPF)

2020-02-28 03:55发布

问题:

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()

Where name would evaluate to "MyTestStyle."

Is this possible?

回答1:

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

you can call it using the following

string name = ResourceHelper.FindNameFromResource(this.Resources, defaultStyle);

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 ?)



回答2:

I had to change the example above slightly to get it work for me, since I use MergedDictionaries. If the above example gives you 0 results, try this:

  //Called by FindNameFromResource(aControl.Style) 
    static public string FindNameFromResource(object resourceItem) 
    {

        foreach (ResourceDictionary dictionary in App.Current.Resources.MergedDictionaries)
        {
            foreach (object key in dictionary.Keys)
            {
                if (dictionary[key] == resourceItem)
                {
                    return key.ToString();
                }
            }
        }
        return null;
    }


回答3:

Without searching resource dictionaries, I don't think this is possible as x:Key is part of the XAML markup grammar and has no relevance when you have a reference to a Style or DataTemplate or anything you've retrieved.

Have a look at the MSDN document on x:Key



回答4:

Probably not using the Style object, but if you go stumping around in the ResourceDictionary containing your style you can get the x:Key.



回答5:

The IF statement needs to compare strings as below

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

            return null;
        }


标签: .net wpf styles