简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM