How can I specify multiple DataTemplate in windows.resources for use by a ContentControl

1.1k Views Asked by At

How can I specify multiple DataTemplate in windows.resources for use by a ContentControl? My code:

<Window.Resources>
    <DataTemplate x:Key="CustomerTemplate" DataType="{x:Type local:Customer}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FirstName}"/>
            <TextBlock Text=" ("/>
            <TextBlock Text="{Binding Occupation}"/>
            <TextBlock Text=")"/>
        </StackPanel>
    </DataTemplate>
    <DataTemplate x:Key="PersonTemplate" DataType="{x:Type local:Person}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FirstName}"/>
            <TextBlock Text=" - "/>
            <TextBlock Text="{Binding LastName}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

Thank you so much!

2

There are 2 best solutions below

0
On

Use DataTemplateSelector to return the Datatemplate you want to be applied..

<ContentControl ContentTemplateSelector="{StaticResource MyTemplateSelector}"/>

here MYtemplateselector is DataTemplateSelector, in Select() method of selector you can check for the property bound to contentcontrol and return the corresponding Datatemplate.

Thanks

0
On

Remove x:Key from DataTemplate and try this:

<ContentControl Name="CustomerContentControl">
    <local:Customer />
</ContentControl>

<ContentControl Name="PersonContentControl">
    <local:Person />
</ContentControl>

In this article, Josh Smith show, how to get access the elements that are in the DataTemplate:

How to use FindName with a ContentControl