如何修改DataGridViewCheckBoxColumn复选框选中后的背景颜色?
解决DataGridViewCheckBoxColumn选中背景色无法修改的问题
你之前通过CellTemplate.Style修改颜色无效的原因是:DataGridViewCheckBoxCell的选中高亮属于系统原生绘制逻辑,常规的样式设置无法覆盖这部分渲染行为。以下是几种可行的解决方案:
方法一:重写DataGridViewCheckBoxCell自定义绘制
这是最精准的解决方案,通过自定义单元格类型完全控制绘制逻辑:
public class CustomCheckBoxCell : DataGridViewCheckBoxCell { protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { // 先绘制单元格基础样式(边框、默认背景) base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border); // 处理选中状态的背景填充 if ((elementState & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { using (Brush customBrush = new SolidBrush(WinFormsUITheme.styleColor)) { graphics.FillRectangle(customBrush, cellBounds); } } // 绘制复选框和内容,避免被背景覆盖 base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.ErrorIcon); } }
初始化列时使用自定义单元格:
var checkBoxColumn = new DataGridViewCheckBoxColumn(); checkBoxColumn.CellTemplate = new CustomCheckBoxCell(); dataGridView1.Columns.Add(checkBoxColumn);
方法二:通过CellPainting事件手动绘制
如果不想重写单元格,可直接处理DataGridView的CellPainting事件,针对CheckBox列做单独处理:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { // 仅处理有效行/列的CheckBox单元格,且处于选中状态 if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && dataGridView1.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn && (e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { // 填充自定义选中背景色 e.Graphics.FillRectangle(new SolidBrush(WinFormsUITheme.styleColor), e.CellBounds); // 绘制复选框、边框等内容,避免被背景覆盖 e.Paint(e.ClipBounds, DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.Border | DataGridViewPaintParts.ErrorIcon); // 标记为已处理,阻止默认绘制逻辑 e.Handled = true; } }
全局主题修改的说明
若要修改整个项目的默认选中高亮颜色,可修改系统颜色,但此操作会影响所有控件的选中样式,并非针对单个DataGridView的专属方案:
// 修改全局控件选中高亮色,注意影响范围是整个应用的系统控件 SystemColors.ControlHighlight = WinFormsUITheme.styleColor;
内容的提问来源于stack exchange,提问作者r-m85
相关产品推荐
相关产品推荐

