Hemisphera
Hemisphera

Reputation: 876

WPF ControlTemplate AND DataTemplate

I have ListView where I would like to apply a custom ControlTemplate to it's items. It is defined like this:

<ListView ItemsSource="{Binding MyAwesomeItems}" ...

MyAwesomeItems holds different classes. So I thought to myself: "Well, hello DataTemplates."

To make the contained items look the way I want them to, I have defined a ControlTemplate like this:

<ListView.ItemContainerStyle>
  <Style TargetType="ListViewItem">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="ListViewItem">
          <Border><ContentControl Content="{TemplateBinding Content}"/></Border>
        </ControlTemplate>            
      </Setter.Value>
    </Setter>
  </Style>
</ListView.ItemContainerStyle>

I have used ContentControl with Binding to TemplateBinding Content. I expected that WPF would then insert my items inside that ContentControl, using whatever DataTemplate I have defined for it.

But instead, it looks like WPF just uses the items .ToString() and does not apply any DataTemplates. Is this intended behaviour?

What I want to achieve is: Have a list of items, where the container of each item looks exactly the way I want and the content of that container comes from the DataTemplate.

Upvotes: 3

Views: 1688

Answers (1)

Tobias Brandt
Tobias Brandt

Reputation: 3413

In a ControlTemplate for a ContentControl you usually use an empty ContentPresenter tag. In your case:

<ControlTemplate TargetType="ListViewItem">
    <Border>
        <ContentPresenter/>
    </Border>
</ControlTemplate>

The ContentPresenter has a ContentSource property which defaults to "Content" and sets all the necessary properties (Content, ContentTemplate, etc.).

See here for details.

Upvotes: 2

Related Questions