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

如何在WPF DataGrid的内容容器添加左右内边距

WPF DataGrid 内容容器添加左右内边距解决方案

核心实现思路

通过修改DataGrid的ControlTemplate,将表头与行内容区域分离,仅给行内容区域添加内边距容器,同时避免滚动条问题,确保内容自动适配。

自定义DataGrid Style代码

替换你原有的DataGridStyle,以下是完整的XAML实现:

<Style x:Key="DataGridStyle" TargetType="{x:Type DataGrid}">
    <Setter Property="BorderThickness" Value="0"/>
    <Setter Property="Margin" Value="0"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGrid}">
                <Border Background="{TemplateBinding Background}" 
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        SnapsToDevicePixels="True">
                    <ScrollViewer x:Name="DG_ScrollViewer" 
                                  Focusable="False"
                                  HorizontalScrollBarVisibility="Hidden"
                                  VerticalScrollBarVisibility="Hidden">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>

                            <!-- 表头区域:不受内边距影响 -->
                            <DataGridColumnHeadersPresenter x:Name="PART_ColumnHeadersPresenter" 
                                                            Grid.Row="0"/>

                            <!-- 行内容容器:添加左右内边距 -->
                            <Border Grid.Row="1" 
                                    Padding="15,0" <!-- 调整此处数值设置左右内边距,上下可按需修改 --> >
                                <ItemsPresenter x:Name="PART_ItemsPresenter"/>
                            </Border>
                        </Grid>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

关键细节说明

  • 表头与内容分离:通过Grid将表头(PART_ColumnHeadersPresenter)和行内容(PART_ItemsPresenter)放在不同行,表头完全不受内边距影响;
  • 内容容器内边距:用Border包裹ItemsPresenter,通过Padding属性设置左右内边距,所有行内容会统一缩进,无需单独设置单元格样式;
  • 避免滚动条:ScrollViewer设置HorizontalScrollBarVisibility="Hidden"和VerticalScrollBarVisibility="Hidden",同时列使用Width="*"会自动根据容器宽度(减去内边距)分配空间,不会出现横向溢出;
  • 内容自动收缩:列宽度设为*时,会自动适配容器可用宽度(原宽度减去内边距),满足内容随内边距自动收缩的需求。

原DataGrid代码保持不变

你的原有DataGrid代码无需修改,只需确保引用上述自定义的DataGridStyle即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:37:05