Eliza Bennet
Eliza Bennet

Reputation: 179

How can I access a named element of a ControlTemplate through code-behind?

I want to access one of the named elements within the original control template that another element is using, in the code-behind.

This is an example of the XAML code (obviously the original is more complicated, or I'd just be doing this in XAML):

<Window x:Class="Temp.MainWindow" Title="MainWindow">
    <Window.Resources>
        <ControlTemplate x:Key="MyTemplate" TargetType="{x:Type Expander}">
            <Expander Header="Some header">
                <StackPanel>
                    <Grid Name="MyGrid"/>
                </StackPanel>
            </Expander>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <Expander Name="expander" Template="{DynamicResource MyTemplate}"/>
    </Grid>
</Window>

What I've tried:

public MainWindow()
{
    InitializeComponent();
    Grid grid = expander.Template.FindName("MyGrid", expander) as Grid;
}

I've also tried

Grid grid = expander.Template.Resources.FindName("MyGrid") as Grid;

But g is always null.

I've looked at:

The links above are how I got the code I'm working with, but for some reason, g is just always null. Am I doing something wrong with the ContentTemplate? Any help would be appreciated!

Upvotes: 1

Views: 3223

Answers (1)

DotNetRussell
DotNetRussell

Reputation: 9867

You need to wait until the template is applied to the control

protected override OnApplyTemplate()
{
    Grid grid = Template.FindName("YourTemplateName") as Grid;
}

The real problem here is that you're mixing technologies. You're attempting to use something meant for grabbing the template of a lookless control, in the behind code of the main window. I would be surprised if you didn't run into more issues.

Instead, I would suggest looking into How to Create Lookless Controls and redesigning your application. It wouldn't take much effort and it would all play nice together.

Upvotes: 2

Related Questions