67

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!

1
  • 1
    I have the feeling you should rather tell what you are trying to achieve, odds are that you don't have to do what you are asking.
    – flq
    Nov 14, 2011 at 19:05

2 Answers 2

110

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.

1
  • EXCELLENT piece of work. Resolved my issue of accessing a control inside a ControlTemplate of ContextMenu. I spent hours trying to come up with a simpler solution than the several suggested online. Your two liner got me where I was trying to get. Thank you for sharing your knowledge and explaining it to readers like myself.
    – nam
    Jun 17, 2021 at 14:52
25

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.

2
  • 3
    My control was buried deep in a chain of styles and custom templates and this event saved me. Thank you.
    – grinder22
    Dec 8, 2017 at 21:08
  • Thanks, this answer solved it for me as well! It can be so easy sometimes
    – Revox
    Jun 7, 2022 at 15:11

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.