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?
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.
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.
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 ?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With