WPF DataGrid如何为每列添加独立边框,实现适配列宽的效果
WPF DataGrid实现每列独立自适应边框方案
预期效果如下:
核心实现逻辑
不需要额外用Grid嵌套Border,直接重写DataGridColumnHeader、DataGridCell的默认样式,给每列的表头和所有单元格套上统一的边框,边框尺寸会自动跟随列宽变化,无需额外维护外部Grid的列参数。
完整修改代码
<Window x:Class="WpfApp3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp3" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid Background="LightGray"> <DataGrid ItemsSource="{Binding Items}" ColumnWidth="*" AutoGenerateColumns="True" GridLinesVisibility="None" Background="Transparent" Margin="5"> <DataGrid.Resources> <!-- 行基础样式 --> <Style TargetType="{x:Type DataGridRow}"> <Setter Property="Background" Value="Transparent"/> </Style> <!-- 列头样式:带顶部圆角边框 --> <Style TargetType="{x:Type DataGridColumnHeader}"> <Setter Property="Background" Value="Transparent"/> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Padding" Value="10,5"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="DataGridColumnHeader"> <Border CornerRadius="5 5 0 0" BorderThickness="1 1 1 0" BorderBrush="Black" Background="White" Margin="0 0 10 0"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <!-- 普通单元格样式:带左右边框 --> <Style TargetType="{x:Type DataGridCell}"> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Padding" Value="10,5"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="DataGridCell"> <Border BorderThickness="1 0 1 0" BorderBrush="Black" Background="White" Margin="0 0 10 0"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <!-- 最后一行单元格样式:额外加底部圆角 --> <Style TargetType="{x:Type DataGridRow}"> <Style.Triggers> <Trigger Property="IsLastItemInContainer" Value="True"> <Setter Property="CellStyle"> <Setter.Value> <Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="DataGridCell"> <Border CornerRadius="0 0 5 5" BorderThickness="1 0 1 1" BorderBrush="Black" Background="White" Margin="0 0 10 0"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> </DataGrid.Resources> </DataGrid> </Grid> </Window>
效果说明
- 边框完全依附于列元素,列宽调整、列数量增减时边框会自动同步,不会出现错位
- 列间距、圆角大小、边框颜色等参数可以直接修改样式中的
Margin、CornerRadius、BorderBrush属性自定义 - 支持自动生成列和手动定义列两种使用场景,无需额外适配
内容的提问来源于stack exchange,提问作者mister_giga
相关产品推荐
相关产品推荐

