Miral
Miral

Reputation: 13030

How to reference the default style ControlTemplate for ListViewItem in WPF?

In WPF, if I apply a GridView to a ListView, then it will automatically change the Template property of the ListViewItem to a ControlTemplate that uses a GridViewRowPresenter instead of a ContentPresenter. This is usually what you want.

As it happens, though, I have a case where I want to keep the original ContentPresenter, so that it will render the ItemTemplate of the ListView.

(For the curious: I'm doing a parent-child thing where the columns are actually for the child elements, so while I do still have a GridViewRowPresenter, it's inside another list control inside the ItemTemplate of the ListView.)

I can do this by setting an ItemContainerStyle on the ListView, and setting the Template property in that to a custom ControlTemplate, since this will override the style setter that the GridView applies.

However this gets really wordy (especially to keep the selection colours) and it breaks the natural theme support, unless I make duplicate copies of the template for each theme, which is definitely silly.

What I really want to do is to write this:

<Setter Property="Template"
        Value="{StaticResource {FindDefaultControlTemplate ListViewItem}}" />

Where the latter bypasses the ControlTemplate set by the GridView and obtains the ControlTemplate that a normal ListViewItem would have used.

Alternatively, if there's some way to tell a GridView to not alter the ListViewItem style at all, that would also work for my scenario.

This has to work inside XAML.

Upvotes: 2

Views: 1341

Answers (1)

Miral
Miral

Reputation: 13030

It appears that the magic incantation is to set this style:

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem"
           BasedOn="{StaticResource {x:Type ListBoxItem}}" />
</ListView.ItemContainerStyle>

Apparently ListViewItem itself doesn't have a default style, but ListBoxItem does.

And this does override whatever GridView does and makes it use a plain ContentPresenter again.

Upvotes: 2

Related Questions