DataGridView行:选择时半透明选定或行边框

13

我有一个DataGridView,每一行的背景颜色都取决于数据绑定项。但是,当我选择一行时,就看不到它原来的背景颜色了。

为了解决这个问题,我想到了两个解决方案:

我可以使所选内容半透明,这样就能看到两个选定的行是否具有不同的背景颜色。

或者,我可以完全删除所选颜色,并在所选行周围画一个边框。

哪种选项更容易实现?如何做到这一点?

这是一个WinForm应用程序。

编辑:最终我使用了你的代码,adrift。

    private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {
        if (dgv.Rows[e.RowIndex].Selected)
        {
            var row = dgv.Rows[e.RowIndex];
            var bgColor = row.DefaultCellStyle.BackColor;
            row.DefaultCellStyle.SelectionBackColor = Color.FromArgb(bgColor.R * 5 / 6, bgColor.G * 5 / 6, bgColor.B * 5 / 6);
        }
    }

这给人半透明选中颜色的印象。感谢您的帮助!

1个回答

11

如果你想在选定的行周围绘制边框,可以使用DataGridView.RowPostPaintEvent;而要“清除”选择颜色,则可以使用DataGridViewCellStyle.SelectionBackColorDataGridViewCellStyle.SelectionForeColor属性。

例如,如果我像这样设置行单元格样式:

row.DefaultCellStyle.BackColor = Color.LightBlue;
row.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
row.DefaultCellStyle.SelectionForeColor = dataGridView1.ForeColor;

我可以将这段代码添加到RowPostPaintEvent中。

private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    if (dataGridView1.Rows[e.RowIndex].Selected)
    {
        using (Pen pen = new Pen(Color.Red))
        {
            int penWidth = 2;

            pen.Width = penWidth;

            int x = e.RowBounds.Left + (penWidth / 2);
            int y = e.RowBounds.Top + (penWidth / 2);
            int width = e.RowBounds.Width - penWidth;
            int height = e.RowBounds.Height - penWidth;

            e.Graphics.DrawRectangle(pen, x, y, width, height);
        }
    }
}

而选定的行将显示如下:

row with border


我尝试了一下,感觉还不错。但是出现了一个新问题 - 透明选择颜色看起来非常丑陋(文字在旧文本和其他东西上方,很难解释)排序后,所以我会寻找另一个解决方案。 - Jim Carragher
我使用了你的代码来创建半透明的选择颜色 - 请参见编辑。感谢您的帮助! - Jim Carragher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接