public class ExpandableButtonCell : DataGridViewButtonCell
{
public ExpandableButtonCell() : base() // 添加无参数的构造函数
{
}
private bool expanded = false; // 标记单元格是否展开
public bool Expanded { get => expanded; set => expanded = value; }
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)
{
// 计算按钮的绘制区域
int buttonSize = 9;
int buttonX = cellBounds.Left + 2;
int buttonY = cellBounds.Top + 2;
Rectangle buttonRect = new Rectangle(buttonX, buttonY, buttonSize, buttonSize);
// 绘制单元格内容
cellBounds.X += buttonSize - 9;
// 绘制单元格内容
base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
// 检查按钮的右边界是否超出了单元格的右边界
if (buttonRect.Right > cellBounds.Right)
{
// 调整按钮的绘制区域,使其在单元格的边界内
buttonRect.Width = cellBounds.Right - buttonRect.Left;
}
// 绘制按钮
graphics.FillRectangle(Brushes.White, buttonRect);
using (Pen pen = new Pen(Color.Black, 2))
{
graphics.DrawLine(pen, buttonX + 2, buttonY + buttonSize / 2, buttonX + buttonSize - 2, buttonY + buttonSize / 2); // 横线
if (!Expanded)
{
graphics.DrawLine(pen, buttonX + buttonSize / 2, buttonY + 2, buttonX + buttonSize / 2, buttonY + buttonSize - 2); // 竖线
}
graphics.DrawRectangle(pen, buttonX, buttonY, buttonSize, buttonSize);
}
}
protected override void OnContentClick(DataGridViewCellEventArgs e)
{
// 获取点击位置
Point clickPoint = DataGridView.PointToClient(Cursor.Position);
// 判断点击位置是否在按钮区域内
int buttonSize = 10;
int buttonX = this.DataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Left + 2;
int buttonY = this.DataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Top + 2;
Rectangle buttonRect = new Rectangle(buttonX, buttonY, buttonSize, buttonSize);
// 判断点击位置是否在按钮区域内
if (buttonRect.Contains(clickPoint))
{
// 点击按钮时切换展开状态
Expanded = !Expanded;
// 更新单元格样式
this.Style.WrapMode = Expanded ? DataGridViewTriState.True : DataGridViewTriState.False;
this.Style.BackColor = Color.White;
//DataGridView.Rows[e.RowIndex].Cells[5].Style.ForeColor=
// Expanded ? Color.Black : Color.Red ;
if (Expanded)
{
this.DataGridView.Rows[e.RowIndex].DefaultCellStyle.SelectionBackColor = Color.DarkBlue;
// this.Style.ForeColor = Color.Black; // 恢复字体颜色为黑色
}
else
{
this.DataGridView.Rows[e.RowIndex].DefaultCellStyle.SelectionBackColor = Color.DarkBlue;
// this.Style.ForeColor = Color.Black; // 恢复原始字体颜色
}
}
base.OnContentClick(e);
}