ListView 内容上的样式正在应用于 ListView 本身

Style on ListView Contents is getting applied to the ListView itself

我在 WPF/XAML 中遇到了一个奇怪的行为。我的意图是创建这样的东西,使用 Borders、ListViewBorders 的样式:

我认为代码应该是这样的:

<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>

但该代码实际上产生了这个:

这让我玩了一下,我发现了一些非常奇怪的东西。 Border 样式中的 WidthHeight 值正在应用于 ListView 本身!

例如,这段代码:

 <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>

产生这个:

ListView的高度为100像素)

当我在 Style 的值中更改 Height 的值时,我的期望是它适用于 Borders,然后他们忽略它,因为他们设置了自己的高度。换句话说,它应该没有效果。但是当我更改 Height 时,ListView 的高度会发生变化。

为了让事情变得更奇怪,Background 值被正确地应用于 Borders。我对这段代码的工作方式有误解吗?我发现错误了吗?做我想做的事情的正确方法是什么?

我正在使用 Visual Studio 2022、.NET 6、C# 10。

我明白了。 ListView 在内部使用 Border 作为背景。样式正在应用于此 Border,以及作为 ListView.

中项目的 Border

解决方案是使用 Border 以外的类型,或者创建一个包装 Border 的用户控件。 Grid 工作正常:

<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>

产生这个: