gpt4 book ai didi

c# - 在不丢失默认样式的情况下更改 DataGridView 上的 RowHeader 背景颜色

转载 作者:太空狗 更新时间:2023-10-29 23:08:32 26 4
gpt4 key购买 nike

我只想更改某些行标题的背景颜色,而不会丢失 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 样式。有帮助吗?

Grid.EnableHeadersVisualStyles = true

Grid.EnableHeadersVisualStyles = false

最佳答案

在构建 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;

关于c# - 在不丢失默认样式的情况下更改 DataGridView 上的 RowHeader 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17681805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com