How to get the name (key) of the applied template?

I have a template assigned to a button:

<Button x:Name="btn_PatMat" Template="{StaticResource PatMat_Button}" ... 

How can I get the Key/String/Name this template from the specified button?

pseudo code:

 String = btn_PatMat.Template.???.ToString() 
+4
source share
2 answers

Well, I'm afraid this is not possible because it is not intended by WPF. There are people who wanted to access x:Name , which is similar to x:Key , they all had to give up.

Pls take a look at the SO post and sitelink.

The only workaround I could imagine was to read all the templates from the ResourceDictionary , create an instance of each resource (if possible), find a template (if it is, for example, a style) and compare it with the current instance of the template found in the control. But this seems like a pretty ugly solution, and I'm not sure if it will work without problems.

+1
source

You can not. At least not the way you are trying.

To quote this SO post about x: Key (highlighted by me):

x:Key used for elements that are added as values ​​for the dictionary, most often for styles and other resources that are added to the ResourceDictionary. When setting the x: Key attribute, there is actually no corresponding property on the object or even a set dependency property. It is simply used by XAML to find out which key to use when calling Dictionary.Add.

StaticResources are evaluated at boot time, so as soon as the control loads, the Template property is no longer bound to the binding, but instead is set to a ControlTemplate copy from your resources, and no corresponding property is set on this object.

You can verify this by checking the XAML buttons after loading, using something like XamlWriter.Save to view its XAML line.

The only solution I can think of could work is to skip your .Resources and find a ControlTemplate that equals your Button ControlTemplate . I have not tested this, and it is probably not very practical for large resource libraries, but it might be an option.

But the best solution would probably be to change your logic, so the key value can be accessed in some other way by any object that it needs.

+2
source

All Articles