DataGridViewCheckboxCell 的背景颜色
-
01-10-2019 - |
题
我有一个 DataGridView
绑定到对象列表,并且我使用设置动态单元格背景颜色 CellFormatting
事件,如 这个答案. 。这对于除 DataGridViewCheckboxColumn
. 。当我单击此单元格内部(但在复选框外部)时,单元格背景更改为默认白色。
从视觉上看,细胞选择似乎正在发生,尽管我尽了最大努力阻止它。我的单元格格式代码设置 SelectionBackColor
以及 BackColor
. 。我已经使用禁用单元格选择 CellStateChanged
事件,并且其他列均不可选:
private void PlayerGrid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e) { if (e.StateChanged == DataGridViewElementStates.Selected) e.Cell.Selected = false; }
是否有额外的解决方法来覆盖复选框的单元格行为?
解决方案
我通过将以下代码添加到 CellStateChanged
事件:
if (e.Cell is DataGridViewCheckBoxCell)
e.Cell.Style.BackColor = BackgroundColor(e.Cell.RowIndex);
(BackgroundColor()
根据行计算单元背景颜色。)
这可以治愈问题,但可能会导致创建额外的样式对象,从而为较大或虚拟表引起性能问题。
其他提示
对于我正在做的事情,我更喜欢这种方法。它能够通过鼠标单击或 Tab 键(例如目的)不可知地更改任何 DataGridView 单元格的背景颜色(包括复选框),以突出显示当前选定的单元格。我发现奇怪的是,其他方法没有像其他细胞类型那样对复选框的背景进行着色。在我的示例中,我在 CellFormatting 事件中使用了这种方法,但我相信类似的语法可以在其他地方成功复制。另外,我相信这更接近地回答了 OP 问题,因为它与 CellFormatting 事件相关。
void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (W.mf.dgv.CurrentCell != null && e.RowIndex==W.mf.dgv.CurrentCell.RowIndex & e.ColumnIndex==W.mf.dgv.CurrentCell.ColumnIndex)
{
W.mf.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = Color.YellowGreen;
}
else
{
W.mf.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = W.mf.dgv.DefaultCellStyle.SelectionBackColor;
}
}
不隶属于 StackOverflow