Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

styles

wpf

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?

like image 254
Mark Carpenter Avatar asked Feb 11 '09 20:02

Mark Carpenter


People also ask

Where is style defined in WPF?

Styles are defined in the resource dictionary and each style has a unique key identifier and a target type. Inside <style> you can see that multiple setter tags are defined for each property which will be included in the style.

What is code behind in WPF?

Code-behind is a term used to describe the code that is joined with markup-defined objects, when a XAML page is markup-compiled. This topic describes requirements for code-behind as well as an alternative inline code mechanism for code in XAML.


1 Answers

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

like image 59
MrTelly Avatar answered Oct 03 '22 08:10

MrTelly