Reputation: 364
I have a template assigned to a button:
<Button x:Name="btn_PatMat" Template="{StaticResource PatMat_Button}" ...
How can I retrieve the Key/String/Name
of this template from said button?
Pseudocode:
String = btn_PatMat.Template.???.ToString()
Upvotes: 4
Views: 107
Reputation: 132618
You can't. At least not in the way you're trying.
To quote from this SO post about x:Key (emphasis mine):
x:Key
is used for items that are being added as values to a dictionary, most often for styles and other resources that are being added to a ResourceDictionary. When setting the x:Key attribute, there is actually no corresponding property on the object or even an attached dependency property being set. It is simply used by the XAML processor to know what key to use when calling Dictionary.Add.
StaticResources
are evaluated during loading, so once the control loads, the Template
property is no longer set to a binding, but is instead set to a copy of the ControlTemplate
from your Resources, and no corresponding property on that object is set to the key.
You can verify this by checking out the XAML of the button after it's loaded, by using something like XamlWriter.Save to view it's XAML string.
The only solution I can think of that might work would be to loop through your .Resources
, and find a ControlTemplate
that is equal to your Button's ControlTemplate
. I haven't tested this, and it probably isn't very practical for large resource libraries, but it may be an option.
But a better solution would probably be to change your logic so the key value can be accessed some other way by whatever object needs it.
Upvotes: 2
Reputation: 4865
Well I'm afraid that's not possible because it's not intended by WPF. There are some people which wanted to get access to x:Name
which is similar to x:Key
, they all had to give up.
Pls have a look at this SO post and this additional link.
The only workaround I could imagine is reading all templates from the ResourceDictionary, instantiate each resource (if possible), find the template (if it's e.g. a style) and compare it with the current instance of the template found in the control. But this seems to be a pretty ugly solution and I'm not sure if it'll work without any problems.
Upvotes: 1