Home > database >  Style on ListView Contents is getting applied to the ListView itself
Style on ListView Contents is getting applied to the ListView itself

Time:11-13

I've encountered a strange behaviour in WPF/XAML. My intent is to create something like this, using Borders, a ListView, and a style for the Borders:

enter image description here

This is what I think the code should be:

<ListView HorizontalAlignment="Right" Margin="20">
     <ListView.Resources>
        <Style TargetType="Border">
           <Setter Property="Height" Value="20"/>
           <Setter Property="Width" Value="150"/>
           <Setter Property="Background" Value="Blue"/>
        </Style>
     </ListView.Resources>
     <Border/>
     <Border/>
  </ListView>

But that code actually produces this:

enter image description here

This lead me to play around a bit and I found something really strange. The Width and Height values in the Style for the Borders are getting applied to the ListView itself!

For example, this code:

 <ListView HorizontalAlignment="Right" Margin="20">
     <ListView.Resources>
        <Style TargetType="Border">
           <Setter Property="Height" Value="100"/>//this should do nothing because the borders set their own height
           <Setter Property="Background" Value="Blue"/>
        </Style>
     </ListView.Resources>
     <Border Height="20" Width="150"/>
     <Border Height="20" Width="150"/>
  </ListView>

Produces this:

enter image description here (The height of the ListView is 100 pixels)

When I change the value of Height in the value of the Style, my expectation is that it applies to the Borders, who then ignore it because they set their own heights. In other words it should have no effect. But When I change Height, the height of the ListView changes.

To make things weirder, the Background value is properly being applied to the Borders. Do I have a misunderstanding about how this code should work? Have I found a bug? What is the right way to do what I am trying to do?

I am using Visual Studio 2022, .NET 6, C# 10.

CodePudding user response:

I figured it out. ListView uses a Border internally for its background. The Style is getting applied to this Border, as well as the Borders that are items in the ListView.

The solution is to use a type other than Border, or to make a user control that wraps Border. Grid works just fine:

<ListView HorizontalAlignment="Right" Margin="20">
     <ListView.Resources>
        <Style TargetType="Grid">
           <Setter Property="Height" Value="20"/>
           <Setter Property="Width" Value="150"/>
           <Setter Property="Background" Value="Blue"/>
        </Style>
     </ListView.Resources>
     <Grid/>
     <Grid/>
  </ListView>

Produces this:

enter image description here

  • Related