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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With