Access an element from DataTemplate

2k views Asked by At
<Window x:Class="GeneratedTemplateDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow">
    <Window.Resources>

        <DataTemplate x:Key="FirstTemplate">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Button Content="simple button1" />
                <DataGrid x:Name="dataGridFromDataTemplate" Grid.Row="1" />
            </Grid>
        </DataTemplate>
        <DataTemplate x:Key="SecondTemplate">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Button Content="simple button2" />
                <DataGrid x:Name="dataGridFromDataTemplate" Grid.Row="1" Background="CadetBlue"/>
            </Grid>
        </DataTemplate>

        <Style x:Key="MyContentControlStyle" TargetType="{x:Type ContentControl}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=TemplateOneToApply}" Value="True">
                    <Setter Property="ContentTemplate" Value="{DynamicResource FirstTemplate}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=TemplateTwoToApply}" Value="False">
                    <Setter Property="ContentTemplate" Value="{DynamicResource SecondTemplate}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>

    <Grid x:Name="MyGrid">
        <ContentControl x:Name="ContentControl" Content="{Binding}" Style="{StaticResource MyContentControlStyle}" />
    </Grid>

</Window>

Where TemplateOneToApply is boolean : when its true i apply the First Template and when its False I apply the Second Template

my question is :

How i can access to dataGridFromDataTemplate element from the code behind

1

There are 1 answers

0
123 456 789 0 On BEST ANSWER

You should not use ContentControl try using ContentPresent

<Grid x:Name="MyGrid">
    <ContentPresenter x:Name="ContentControl" Content="{Binding}" Style="{StaticResource MyContentControlStyle}" />
</Grid>

And behind the code you have to explicitly have to say apply template in order to get it

ContentControl.ApplyTemplate();
var dataGrid = ContentControl.ContentTemplate.FindName("dataGridFromDataTemplate", ContentControl) as DataGrid;