How do I access an element of a control template from within code-behind How do I access an element of a control template from within code-behind wpf wpf

How do I access an element of a control template from within code-behind


You need to get the template and locate the control by name on the templated control, something like:

var template = MyList.Template;var myControl = (MyControl)template.FindName("MyControlName", MyList);

Templates are just that: Abstract descriptions of what is to be created, the controls in templates only exist in the context of something that is being templated.


Note that you should only ever access the elements within a control template if you are authoring the control that the template is for. Access from outside should be done via bound properties and methods.

For data templates this is similar. All the things you need to access should be bound to an object and access should then be through said object. This is especially true in cases of item controls which virtualize their items, so the elements do not even exist most of the time.


U also can get control from every template by adding Loaded event in control and then in code assign sender of event to some variable.