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
相关产品推荐
相关产品推荐

