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

WPF 如何为整个 ListView 控件添加内部横竖网格线

实现方案

在现有代码基础上补充表头样式和单元格样式,给列头、单元格添加右侧边框即可实现横竖网格线效果,完整修改后代码如下:

<ListView DockPanel.Dock="Top" ItemsSource="{Binding Columns}" Margin="0,20,0,0"
          HorizontalAlignment="Center">
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="BorderBrush" Value="Black" />
            <Setter Property="BorderThickness" Value="0,0,0,1" />
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            <Setter Property="VerticalContentAlignment" Value="Stretch" />
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.Resources>
        <!-- 表头样式,添加右侧和下侧边框 -->
        <Style TargetType="{x:Type GridViewColumnHeader}">
            <Setter Property="BorderBrush" Value="Black"/>
            <Setter Property="BorderThickness" Value="0,0,1,1"/>
            <Setter Property="Padding" Value="4,2"/>
            <!-- 去掉表头默认的悬停高亮效果,不需要可以删除以下Setter -->
            <Setter Property="Background" Value="#F0F0F0"/>
        </Style>
        <!-- 单元格通用模板,添加右侧边框形成纵向分割线 -->
        <DataTemplate x:Key="GridCellTemplate">
            <Border BorderBrush="Black" BorderThickness="0,0,1,0" Padding="4,2">
                <ContentPresenter Content="{Binding}"/>
            </Border>
        </DataTemplate>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Столбец 1" Width="100" CellTemplate="{StaticResource GridCellTemplate}" DisplayMemberBinding="{Binding Path=Column1}" />
            <GridViewColumn Header="Столбец 2" Width="100" CellTemplate="{StaticResource GridCellTemplate}" DisplayMemberBinding="{Binding Path=Column2}" />
            <GridViewColumn Header="Столбец 3" Width="100" CellTemplate="{StaticResource GridCellTemplate}" DisplayMemberBinding="{Binding Path=Column3}" />
            <GridViewColumn Header="Столбец 4" Width="100" CellTemplate="{StaticResource GridCellTemplate}" DisplayMemberBinding="{Binding Path=Column4}" />
            <GridViewColumn Header="Столбец 5" Width="100" CellTemplate="{StaticResource GridCellTemplate}" DisplayMemberBinding="{Binding Path=Column5}" />
            <GridViewColumn Header="Столбец 6" Width="100" CellTemplate="{StaticResource GridCellTemplate}" DisplayMemberBinding="{Binding Path=Column6}" />
        </GridView>
    </ListView.View>
</ListView>

补充说明

  • 原有横向网格线逻辑保留,通过ListViewItem的下边框实现
  • 纵向网格线通过单元格和表头的右侧边框实现,你可以修改BorderBrush和BorderThickness属性调整线条的颜色和粗细
  • 如果不需要最后一列的右侧边框,可以单独给最后一个GridViewColumn设置不带右边框的CellTemplate,同时给最后一个表头单独设置BorderThickness="0,0,0,1"
  • 该方案不会影响原有数据绑定、行选中等交互逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:21:00