我有一个 DataGridView,其中每行的背景根据数据绑定项而不同。但是,当我选择一行时,我无法再看到它原来的背景颜色。
为了解决这个问题,我想到了两个解决方案:
我可以使选择半透明,从而可以查看两个选定的行是否具有不同的背景颜色。
或者;我可以完全删除选择颜色,并在所选行周围绘制边框。
哪种选择更容易?我该如何做到这一点?
这是一个 WinForm 应用程序。
编辑:我最终使用了你的一些代码,漂流
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);
}
}
这给人一种半透明选择颜色的印象。感谢您的帮助!
如果要在选定的行周围绘制边框,可以使用DataGridView.RowPostPaintEvent http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowpostpaint.aspx,并“清除”选择颜色,您可以使用DataGridViewCellStyle.SelectionBackColor http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcellstyle.selectionbackcolor.aspx and DataGridViewCellStyle.SelectionForeColor http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcellstyle.selectionforecolor.aspx特性。
例如,如果我像这样设置行单元格样式
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);
}
}
}
选定的行将显示如下:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)