DataGridView行:半透明选择或选择中的行边框 [英] DataGridView row: Semi-transparent selection or row border on selection
问题描述
我有一个DataGridView,其中每行的背景根据数据绑定项的不同而不同。但是,当我选择一行时,不再能看到其原始背景颜色。
I have a DataGridView where the background of each row is different depending on the data bound item. Though, when I select a row, I can no longer see its original background color.
为解决此问题,我想到了两种解决方案:
To solve this, I have thought of two solutions:
我可以将选择内容设为半透明,从而可以查看两个选定的行是否具有不同的背景颜色。
I can make the selections semi-transparent, making it possible to see if two selected rows have different background colors.
或者;我可以完全删除选择颜色,并在选定的行周围绘制边框。
Or; I can remove the selection colors entirely, and draw a border around the selected rows.
哪个选项更简单,怎么做?
What option is easier and how can I do this?
这是一个WinForm应用程序。
It's a WinForm app.
编辑:我最终使用了一些代码,漂流了
I ended up using some of your code, 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);
}
}
这给人以半透明选择颜色的印象。谢谢您的帮助!
This gives the impression of a semi-transparent selection color. Thanks for your help!
推荐答案
如果要在选定的行周围绘制边框,可以使用 DataGridView.RowPostPaintEvent ,并清除选择颜色,您可以使用 DataGridViewCellStyle.SelectionBackColor 和 DataGridViewCellStyle.SelectionForeColor 属性。
If you want to draw a border around selected rows, you can use the DataGridView.RowPostPaintEvent, and to 'clear' the selection colors, you can use the DataGridViewCellStyle.SelectionBackColor and DataGridViewCellStyle.SelectionForeColor properties.
例如,如果我这样设置行单元格样式
For example, if I set the row cell style like this
row.DefaultCellStyle.BackColor = Color.LightBlue;
row.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
row.DefaultCellStyle.SelectionForeColor = dataGridView1.ForeColor;
我可以将此代码添加到 RowPostPaintEvent
I can add this code to the 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);
}
}
}
,将显示选定的行像这样:
and a selected row will display like this:
这篇关于DataGridView行:半透明选择或选择中的行边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!