You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI ListView项高度低于阈值不生效,如何实现高度约18的紧凑列表?

如何创建项总高度约18的紧凑WPF ListView?

尽管已经为ListView的项模板设置了高度、最小高度、边距和内边距等属性,但ListView存在默认的最小高度阈值(约20-30范围),低于该阈值时,ListView会自动创建固定高度的容器,自定义项模板仅在容器内浮动。比如下方XAML代码中,TextBlock的FontSize设为12,但实际项容器高度是它的2.5倍以上。

项容器高度超出预期的示例截图

用户原始代码:

<ListView
    x:Name="MyListView"
    Margin="15,15,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid
                Height="15"
                MinHeight="15"
                Margin="0"
                Padding="0"
                BorderThickness="0">
                <TextBlock
                    Height="15"
                    MinHeight="15"
                    Margin="0"
                    Padding="0"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Center"
                    FontSize="12"
                    Text="{Binding}" />
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.Items>
        <x:String>Item 1</x:String>
        <x:String>Item 2</x:String>
    </ListView.Items>
</ListView>

要实现高度约18的紧凑ListView,核心是修改ListViewItem的默认样式——默认的ListViewItem自带内边距和最小高度限制,仅修改ItemTemplate无法突破这个限制。

解决方案代码

<ListView
    x:Name="MyListView"
    Margin="15,15,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch">
    <!-- 自定义项容器样式,覆盖默认限制 -->
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="Height" Value="18"/>
            <Setter Property="MinHeight" Value="18"/>
            <Setter Property="Margin" Value="0"/>
            <Setter Property="Padding" Value="0"/>
            <!-- 可选:移除默认选中边框、焦点样式,保持视觉紧凑 -->
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock
                Height="18"
                MinHeight="18"
                Margin="0"
                Padding="0"
                HorizontalAlignment="Left"
                VerticalAlignment="Center"
                FontSize="12"
                Text="{Binding}" />
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.Items>
        <x:String>Item 1</x:String>
        <x:String>Item 2</x:String>
    </ListView.Items>
</ListView>

说明

  1. 通过ItemContainerStyle直接控制ListViewItem的高度、内边距和外边距,彻底突破默认的最小高度阈值;
  2. 可以移除ItemTemplate中多余的Grid容器,直接用TextBlock作为根控件,进一步简化结构;
  3. 若需要更极致的紧凑效果,还可以调整TextBlock的LineHeight属性,配合FontSize实现更精准的垂直布局。

内容的提问来源于stack exchange,提问作者E. A. Bagby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 19:55:13