You need to enable JavaScript to run this app. WPF中ListView使用UniformGrid作为项面板时如何让子项横竖间距相等
优惠活动
大模型
产品
解决方案
定价
更多

WPF中ListView使用UniformGrid作为项面板时如何让子项横竖间距相等

问题根因

该问题由WPF ListView 自带的默认容器样式导致:ListViewItem 内置了不为0的左右边距,且默认 HorizontalContentAlignment 属性为Stretch,会让每个单元格的内容在水平方向额外撑开空间,最终表现为水平间距大于垂直间距。

修复步骤
  • 第一步:重写ListView的ItemContainerStyle,清除容器默认边距,强制对齐属性
<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="Padding" Value="0"/>
        <Setter Property="Margin" Value="0"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="BorderThickness" Value="0"/>
    </Style>
</ListView.ItemContainerStyle>
  • 第二步:显式指定UniformGrid的尺寸属性,避免自动计算产生多余留白
<ListView.ItemsPanel>
    <ItemsPanelTemplate>
        <UniformGrid 
            Columns="你实际需要的列数"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"/>
    </ItemsPanelTemplate>
</ListView.ItemsPanel>
  • 第三步:确认自定义CheckBox样式无额外边距,显式固定宽高
<Style TargetType="CheckBox">
    <Setter Property="Width" Value="26"/>
    <Setter Property="Height" Value="26"/>
    <Setter Property="Padding" Value="0"/>
    <Setter Property="Margin" Value="0"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="CheckBox">
                <Grid Background="Yellow" Width="26" Height="26">
                    <Border Width="26" Height="26">
                        <Ellipse Fill="Gray"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
优化建议

如果你不需要使用ListView的选中、排序、分组等专属特性,直接替换为ItemsControl即可完全避免容器默认样式的干扰,布局逻辑更简洁。

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 22:36:02