在构建 DataGridView
时,默认情况下应该已经定义了行标题的默认样式。因此,我会使用以下代码:
if ( )
{
DataGridViewCellStyle rowStyle; // = Grid.RowHeadersDefaultCellStyle;
rowStyle = Grid.Rows[i].HeaderCell.Style;
rowStyle.BackColor = Color.Wheat;
Grid.Rows[i].HeaderCell.Style = rowStyle;
}
这样,您可以使用预定义的样式填充
rowStyle
,然后仅更改您想更改的部分。看看这是否解决了您的问题。
//编辑
由于您希望保留默认的Windows DataGridView的其他样式,因此您还需要设置更多样式的其他参数。请参见
此帖子。
或者尝试这个。在初始化时:
dataGridView1.CellPainting +=
new DataGridViewCellPaintingEventHandler (dataGridView_CellPainting);
然后,使用类似以下方式创建处理程序函数:
void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
DataGridView dv = sender as DataGridView;
DataGridViewCellStyle rowStyle;
if (e.ColumnIndex == -1)
{
e.PaintBackground(e.CellBounds, true);
e.Handled = true;
if ()
{
rowStyle = dv.Rows[e.RowIndex].HeaderCell.Style;
rowStyle.BackColor = Color.Wheat;
dv.Rows[e.RowIndex].HeaderCell.Style = rowStyle;
using (Brush gridBrush = new SolidBrush(Color.Wheat))
{
using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
e.PaintContent(e.ClipBounds);
e.Handled = true;
}
}
}
}
}
}
这段代码基于这篇文章。你只需要为鼠标悬停和选中状态创建更多的绘制条件。但是这应该对你有用。
记得移除:Grid.EnableHeadersVisualStyles = false;
或者强制使用:Grid.EnableHeadersVisualStyles = true;
。
paint
处理程序修改单个行。 - CaptainBliGrid.EnableHeadersVisualStyles = false;
,它必须为 true 才能保持实际的默认样式。 - CaptainBli