How to show a data template on a content control?

Darf Zon picture Darf Zon · Jan 22, 2012 · Viewed 23k times · Source

Imagine that in one data template, I have a textBox, and another data template, I've got two textboxes.

According to this, in the view has a checkbox, and show each template.. is this possible?

Sorry if my question is so doubt, I've investigate it but I didn't find out.

I was did this, I know this is useless, but is only for testing.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
        <DataTemplate DataType="{x:Type ContentControl}" x:Key="T1">
            <StackPanel>
                <TextBox Height="20" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate DataType="{x:Type ContentControl}" x:Key="T2">
            <StackPanel>
                <TextBox Height="20" />
                <TextBox Height="20" />
            </StackPanel>
        </DataTemplate>
    </Window.Resources>


    <Grid>
        <ContentControl Template="{StaticResource T1}" />
    </Grid>
</Window>

Answer

JayP picture JayP · Jan 22, 2012

Instead of setting the Template property, try this:

<ContentControl ContentTemplate="{StaticResource T1}" />