重写DataGridView控件实现渐变标题栏 - (第十三讲)
视频讲解如下:
网盘下载,提取码:pt2b
https://pan.baidu.com/s/1C2ri-X89szdMtxfgc-feGg
这里给大家讲解一下如何重写DataGridView控件实现渐变标题栏
DataGridView控件重写后的效果如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WindowsFormsApp
{
public class MyDataGridView :DataGridView
{
/// <summary>
/// 奇数行颜色
/// </summary>
public Color ColColor { get; set; } = Color.FromArgb(237, 244, 252);
/// <summary>
/// 标题栏背景色
/// </summary>
public Color HeadrColor { get; set; } = Color.FromArgb(142, 207, 247);
public MyDataGridView()
{
this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
}
protected override void OnCreateControl()
{
this.AlternatingRowsDefaultCellStyle.BackColor = ColColor;
this.ColumnHeadersDefaultCellStyle.Font = new Font("Microsoft YaHei UI", 10.5f, FontStyle.Bold);
this.DefaultCellStyle.Font = new Font("Microsoft YaHei UI", 10.5f);
this.RowsDefaultCellStyle.Font = new Font("Microsoft YaHei UI", 10.5f);
}
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
base.OnCellPainting(e);
if (e.RowIndex == -1)
{
// 设置标题行渐变色背景
using (LinearGradientBrush brush = new LinearGradientBrush(e.CellBounds,
Color.White, HeadrColor, LinearGradientMode.Vertical))
{
e.Graphics.FillRectangle(brush, e.CellBounds);
}
Rectangle border = e.CellBounds;
border.Offset(new Point(-1, -1));
e.Graphics.DrawRectangle(Pens.Gray, border);
e.PaintContent(e.CellBounds);
e.Handled = true;
}
}
}
}