tags:

views:

2558

answers:

4

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  A: 

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

Ray Booysen
+1  A: 

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

sixlettervariables
+2  A: 

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

MrTelly
Or just have it start from some FrameworkElement and work breadth-first through the visual tree.
sixlettervariables
A: 

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