Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to access a user control which is inside the control template of a content control. Specifically:

  <ContentControl x:Name="MyList" >         <ContentControl.Template>             <ControlTemplate x:Name="MyControlTemplate">                 <Border RenderTransformOrigin="0,0" x:Name="border">                     <UserControls:MyControl x:Name="MyControlName" Width="100" ViewModel="{Binding}" /> 

I can access this.MyList but it says this.MyControlName is not found. How do I access the MyControlName object from code-behind in this situation?

Thanks!

like image 656
Locksleyu Avatar asked Nov 14 '11 19:11

Locksleyu


People also ask

How do you access elements that are embedded inside the ControlTemplate?

When you declare elements inside the ControlTemplate, use the 'Name' of each control for identifying it from the outside. We can then use the 'FindName' function for finding the resource. An example shown below is for accessing the TextBlock of a button.

What is the difference between control template and data template?

A ControlTemplate will generally only contain TemplateBinding expressions, binding back to the properties on the control itself, while a DataTemplate will contain standard Binding expressions, binding to the properties of its DataContext (the business/domain object or view model).


2 Answers

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.

like image 32
Dawid Jablonski Avatar answered Sep 28 '22 00:09

Dawid Jablonski


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.

like image 80
H.B. Avatar answered Sep 27 '22 23:09

H.B.