我只希望更改某些行标题的背景颜色而不会丢失DataGridView附带的炫酷默认窗口样式:
Grid.EnableHeadersVisualStyles = false;
for(int i=0; i<Grid.Rows.Count; i++)
{
if ( /*I want to change this row */)
{
DataGridViewCellStyle rowStyle = Grid.RowHeadersDefaultCellStyle;
rowStyle.BackColor = Color.Wheat;
Grid.Rows[i].HeaderCell.Style = rowStyle;
}
}
一旦我这样做,我就会失去对列的MouseOver蓝色效果,并且列上的排序箭头显示为灰色.
我试图将列标题设置为defaultColHeaderStyle无济于事.行标题更改为所需的颜色,其列标题将失去其光滑的Windows样式.有帮助吗?
解决方法:
在构建DataGridView时,应已经定义了行标题的默认样式.所以我会用:
if ( /*I want to change this row */)
{
DataGridViewCellStyle rowStyle; // = Grid.RowHeadersDefaultCellStyle;
rowStyle = Grid.Rows[i].HeaderCell.Style;
rowStyle.BackColor = Color.Wheat;
Grid.Rows[i].HeaderCell.Style = rowStyle;
}
这样,您可以使用预定义样式填充rowStyle,然后仅更改要更改的部分.看看这是否能解决您的问题.
//编辑
如果您希望保留默认Windows DataGridView的其他样式,则还需要设置样式的其他更多参数.见this post.
或试试这个.初始化时:
dataGridView1.CellPainting +=
new DataGridViewCellPaintingEventHandler (dataGridView_CellPainting);
然后用以下内容创建处理函数:
void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
DataGridView dv = sender as DataGridView;
DataGridViewCellStyle rowStyle;// = dv.RowHeadersDefaultCellStyle;
if (e.ColumnIndex == -1)
{
e.PaintBackground(e.CellBounds, true);
e.Handled = true;
if (/*I want to change this row */)
{
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))
{
// Clear cell
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
//Bottom line drawing
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
// here you force paint of content
e.PaintContent(e.ClipBounds);
e.Handled = true;
}
}
}
}
}
}
此代码基于this post.您只需要为鼠标悬停和选定状态创建更多绘制条件.但这对你有用.
记得删除:Grid.EnableHeadersVisualStyles = false;或强制它:Grid.EnableHeadersVisualStyles = true;.