I've encountered a strange behaviour in WPF/XAML. My intent is to create something like this, using Border
s, a ListView
, and a style for the Border
s:
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:
This lead me to play around a bit and I found something really strange. The Width
and Height
values in the Style for the Border
s 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:
(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 Border
s, 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 Border
s. 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 Border
s 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: