1

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!

Community
  • 1
  • 1
Eliza Bennet
  • 179
  • 4
  • 17

1 Answers1

2

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.

DotNetRussell
  • 9,716
  • 10
  • 56
  • 111
  • Thanks, but that didn't work (`grid` is still `null`). I'll look into the Lookless Controls, I'm discovering that I don't understand WPF nearly as well as I thought I did. As a temporary fix, I guess I'll avoid using the templates and just use the same code repeatedly, until I get time to look at that article in more detail. – Eliza Bennet Jul 07 '16 at 12:46
  • @Debra yeah it's not your fault. It takes years to get all of the disciplines you need in order to make everything play nice together. The technologies do mix a little, but once you start doing complex things with them wonky things start happening. If I could point you in a direction it would be to learn the MVVM architecture and learn how to build lookless controls. You'll thank yourself and be way further than most. – DotNetRussell Jul 07 '16 at 12:49