Search code examples
c#xamlwindows-8datatemplatewindows-store

XAML templating data


I have a ListView populated with three different types of items. When I select a ListViewItem in the ListView I want to display data in a template specifically designed for the type of the selected item.

The data is displayed in a different column in the same Grid as the ListView.

My question is, what element should I use to make new Templates for displaying the data for the selected item.

I was hoping it would be possible to set a sort of ItemTemplate property on a Grid, but that is not the case.

<Grid
    x:Name="ItemDetailsGrid"
    DataContext="{Binding SelectedItem}"
    ItemTemplate="{StaticResource {Binding SelectedItem.TemplateName}}">         
</Grid>

What is the correct way of doing this?


Solution

  • I think you are going to need a ContentPresenter

    <ContentPresenter
       x:Name = "ItemDetailsGrid"
       Content = "{Binding SelectedItem}">
       <ContentPresenter.Resources>
          <DataTemplate DateType="{x:Type Type1}">
              <TextBlock Text="{Binding PropertyA}" />
          </DataTemplate>
          <DataTemplate DateType="{x:Type Type2}">
              <TextBlock Text="{Binding PropertyB}" />
          </DataTemplate>
    </ContentPresenter>
    

    The appropriate template will be chosen based on it's type.