0
<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 元素

4

1 回答 1

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;
于 2013-12-18T21:42:32.683 回答