从DataTemplate访问元素

时间:2013-12-18 21:30:56

标签: wpf datatemplate contenttemplate

<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>

其中TemplateOneToApply是布尔值:当它的真实时我应用第一个模板,当它为假时我应用第二个模板

我的问题是:

我如何从

背后的代码访问dataGridFromDataTemplate元素

1 个答案:

答案 0 :(得分:2)

您不应该使用ContentControl尝试使用ContentPresent

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

在代码背后,您必须明确地说应用模板才能获得它

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