Search code examples
c#wpflistviewgridviewlistviewitem

WPF ListViewItem style broke the data bindings?


I'm kinda new to WPF and I have a binding listview using gridview to display a list of objects and their properties. My entire project uses a custom style from MaterialDesign that gives everything a dark-theme.

I wanted to add doubleclick functionality to the items in my listview and I found that, I can do that by changing the style of ListViewItem. However that overwrote the default style from my MaterialDesign theme, and the items became ugly.

Then I added BasedOn="{StaticResource {x:Type ListViewItem}}" to restore the default style, but then the binding stopped working and it stopped displaying the properties of the objects?

Might there be a better way to add Setters to the style of an element? And how does setting the style change anything about the data bindings?

<ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}"  BasedOn="{StaticResource {x:Type ListViewItem}}">
        <EventSetter Event="MouseDoubleClick" Handler="HitsoundLayer_MouseDoubleClick"/>
    </Style>
</ListView.ItemContainerStyle>
<ListView.View>
    <GridView>
        <GridViewColumn Header="_Name" Width="120" DisplayMemberBinding="{Binding Name}" />
        <GridViewColumn Header="_Amount" Width="90" DisplayMemberBinding="{Binding Times.Count}" />
        <GridViewColumn Header="_SampleSet" Width="120" DisplayMemberBinding="{Binding SampleSetString}" />
        <GridViewColumn Header="_Hitsound" Width="120" DisplayMemberBinding="{Binding HitsoundString}" />
        <GridViewColumn Header="_Sample Path" Width="1000" DisplayMemberBinding="{Binding SamplePath}" />
    </GridView>
</ListView.View>

What I expected was a ListView that looks like as below and has working doubleclick. enter image description here

But what I got was a ListView that looks like as below enter image description here and has working doubleclick.

This is how it looks like without BasedOn="{StaticResource {x:Type ListViewItem}}" enter image description here


Solution

  • You should base your style on the MaterialDesignGridViewItem resource:

    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem" BasedOn="{StaticResource MaterialDesignGridViewItem}">
            <EventSetter Event="MouseDoubleClick" Handler="HitsoundLayer_MouseDoubleClick"/>
        </Style>
    </ListView.ItemContainerStyle>