Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 214
Hemisphera Avatar asked Jan 22 '26 04:01

Hemisphera


1 Answers

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.

like image 157
Tobias Brandt Avatar answered Jan 23 '26 20:01

Tobias Brandt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!