Goran
Goran

Reputation: 6518

Handling different item templates that share the same content

I have two custom ItemTemplates for the ListBox, one for the regular items, and one for the selected item. An example of how would I handle this is:

<ListBox.ItemContainerStyle>
  <Style TargetType="ListBoxItem">
    <Setter Property="ContentTemplate" Value="{StaticResource Template1}" />
    <Style.Triggers>
      <Trigger Property="IsSelected" Value="True">
        <Setter Property="ContentTemplate" Value="{StaticResource Template2}" />
      </Trigger>
    </Style.Triggers>
  </Style>
</ListBox.ItemContainerStyle>

Template1 and Template2 are very similar:

<DataTemplate x:Key="Template1">
  <SameContent />
  <DifferentContent1 />
</DataTemplate>

<DataTemplate x:Key="Template2">
  <SameContent />
  <DifferentContent2 />
</DataTemplate>

So, is it a proper way to duplicate the code for the SameContent (which is like a bunch of TextBlocks, Panels, etc) in both templates, or it is a better approach to have only one template, but switch the DifferentContent based on the IsSelected property, or...?

if second approach, how would it be properly done?

Upvotes: 2

Views: 52

Answers (1)

Bahman_Aries
Bahman_Aries

Reputation: 4798

Obviously duplicating the code is not a very good solution. A better approach is to define another DataTemplate as your common content and then use ContentPresenter to present it:

<Window.Resources>
    <DataTemplate x:Key="CommonTemplate">
        <TextBlock Text="{Binding CommonProperty1}" />
        <TextBlock Text="{Binding CommonProperty2}" />
    </DataTemplate>
    <DataTemplate x:Key="Template1" >
        <StackPanel>
            <ContentPresenter ContentTemplate="{StaticResource CommonTemplate}"/>
            <TextBlock Text="{Binding Template1Property1}"/>
            <TextBlock Text="{Binding Template1Property2}"/>
        </StackPanel>
    </DataTemplate>
    <DataTemplate x:Key="Template2" >
        <StackPanel>
            <ContentPresenter ContentTemplate="{StaticResource CommonTemplate}"/>
            <TextBlock Text="{Binding Template2Property1}"/>
            <TextBlock Text="{Binding Template2Property2}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

Upvotes: 1

Related Questions