Can i get the key of a style in code-behind? (WPF)
Solution 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 ?)
Solution 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;
}
Solution 3
Probably not using the Style object, but if you go stumping around in the ResourceDictionary containing your style you can get the x:Key.
Solution 4
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
Mark Carpenter
Programmer: C#, VB.NET, ASP.NET, WinForms, WPF, SQL Server
Updated on August 30, 2020Comments
-
Mark Carpenter over 3 years
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?
-
Sam about 15 yearsOr just have it start from some FrameworkElement and work breadth-first through the visual tree.