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

WPF C#:如何修改DataGrid行背景色并与控件背景保持一致?

解决WPF DataGrid行背景色与控件背景色一致的问题

要让DataGrid的行背景色和控件自身背景色保持一致,只需给DataGrid添加RowStyle,将行的背景设置为与控件相同的颜色,或者直接设为透明(透明会自动继承控件背景色,后续修改控件背景时无需同步调整行样式)。

以下是修改后的完整XAML代码:

<DataGrid ColumnWidth="*"
          Background="#2c386c"
          BorderThickness="0"
          CanUserAddRows="False"
          ItemsSource="{Binding CustomersList}"
          SelectionChanged="customer_datagrid_SelectionChanged">

    <!-- 列头样式 -->
    <DataGrid.ColumnHeaderStyle>
        <Style TargetType="DataGridColumnHeader">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Foreground" Value="#BCBEE0"/>
            <Setter Property="Padding" Value="10,0,0,10"/>
            <Setter Property="FontFamily" Value="Montserrat"/>
            <Setter Property="FontSize" Value="15"/>
        </Style>
    </DataGrid.ColumnHeaderStyle>

    <!-- 行样式:设置背景与DataGrid一致 -->
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <!-- 方案1:直接用和DataGrid相同的背景色 -->
            <Setter Property="Background" Value="#2c386c"/>
            <!-- 方案2:设为透明,自动继承父控件背景色(更灵活) -->
            <!-- <Setter Property="Background" Value="Transparent"/> -->
            <!-- 可选:自定义选中行颜色,保持风格统一 -->
            <Setter Property="SelectionBrush" Value="#4a5a9a"/>
        </Style>
    </DataGrid.RowStyle>

</DataGrid>

说明:

  • 方案1直接指定与DataGrid相同的颜色值,行背景完全匹配;
  • 方案2使用透明背景,行背景会自动透出DataGrid的背景色,后续修改DataGrid的Background属性时,行背景会同步变化;
  • 若需要保留行选中效果,可调整SelectionBrush的颜色值,避免默认高亮破坏整体深色风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:45:36