Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DataGridViewCheckboxCell的背景色_C#_Winforms_Datagridview_Datagridviewcheckboxcell - Fatal编程技术网

C# DataGridViewCheckboxCell的背景色

C# DataGridViewCheckboxCell的背景色,c#,winforms,datagridview,datagridviewcheckboxcell,C#,Winforms,Datagridview,Datagridviewcheckboxcell,我将一个DataGridView绑定到一个对象列表,并使用CellFormatting事件设置动态单元格背景颜色,如中所示。这适用于除DataGridViewCheckboxColumn之外的所有列。当我在该单元格内(但在复选框外)单击时,单元格背景将更改为默认白色 从视觉上看,细胞选择似乎正在发生,尽管我尽了最大努力阻止它。我的单元格格式代码设置SelectionBackColor以及BackColor。我已使用CellStateChanged事件禁用了单元格选择,其他列均不可选择: priv

我将一个
DataGridView
绑定到一个对象列表,并使用
CellFormatting
事件设置动态单元格背景颜色,如中所示。这适用于除
DataGridViewCheckboxColumn
之外的所有列。当我在该单元格内(但在复选框外)单击时,单元格背景将更改为默认白色

从视觉上看,细胞选择似乎正在发生,尽管我尽了最大努力阻止它。我的单元格格式代码设置
SelectionBackColor
以及
BackColor
。我已使用
CellStateChanged
事件禁用了单元格选择,其他列均不可选择:

private void PlayerGrid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e) { if (e.StateChanged == DataGridViewElementStates.Selected) e.Cell.Selected = false; } 私有void PlayerGrid_CellStateChanged(对象发送方,DataGridViewCellStateChangedEventArgs e) { if(e.StateChanged==DataGridViewElementState.Selected) e、 Cell.Selected=false; }
是否有额外的解决方法来覆盖复选框的单元格行为?

我通过向
CellStateChanged
事件添加以下代码找到了解决方法:

if (e.Cell is DataGridViewCheckBoxCell)
      e.Cell.Style.BackColor = BackgroundColor(e.Cell.RowIndex);
BackgroundColor()
根据行计算单元格背景颜色。)


这解决了问题,但可能会导致创建额外样式对象,从而导致较大或虚拟表的性能问题。

我更喜欢这种方法。它可以不可知地更改任何DataGridView单元格的背景颜色(包括复选框),只需单击鼠标或选项卡即可(例如),以突出显示当前选定的单元格。我发现奇怪的是,其他方法没有给复选框的背景上色,因为其他单元格类型都上色了。在我的示例中,我在CellFormatting事件中使用了这种方法,但我相信类似的语法可以在其他地方成功复制。此外,我认为这更接近于回答OPs问题,因为它与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;

         }
}

进一步信息-我在调试器中捕获了
CellMouseLeave
事件,发现单元格的
InheritedStyle
对于所有四个颜色字段都为零值。