2

在我的Winform 4.5应用程序中,我有一个DataGridView,第一列作为链接​​列。我希望所选链接单元的链接颜色为白色。由于默认情况下选定行(或单元格)的背景颜色为蓝色,并且所有链接的背景颜色也是蓝色,所以当用户选择一行(或链接单元格)时,链接的文本不可读。我试着编写下面的代码,但它并没有改变所选链接单元的链接颜色。SelectionForeColor不适用于DataGridView的DataGridViewLinkColumn中的链接单元格

private void dataGridView1_SelectionChanged(object sender, EventArgs e) 
{ 
    foreach (DataGridViewLinkCell cell in ((DataGridView)sender).SelectedCells) 
    { 
     if (cell.ColumnIndex == 0) 
     { 
      if (cell.Selected) 
      { 
       cell.Style = new DataGridViewCellStyle() 
       { 
        SelectionForeColor = SystemColors.HighlightText 
       }; 
      } 
     } 
    } 
} 

然后我修改了上面的代码,如下所示。但它改变了所有的链接,白色的链接颜色 - 这使得非选择链路小区是因为这些链接的背景色不可读也白:

private void dataGridView1_SelectionChanged(object sender, EventArgs e) 
    { 
     foreach (DataGridViewLinkCell cell in ((DataGridView)sender).SelectedCells) 
     { 
      if (cell.ColumnIndex == 0) 
      { 
       if (cell.Selected) 
       { 
        cell.LinkColor = SystemColors.HighlightText; 
       } 
      } 
     } 
    } 

我通过设置断点检测了两个码在foreach循环中并选择一个链接单元格。我注意到代码确实经历了正确的foreach循环的一次迭代。此外,我已经默认情况下不改变的DataGridViewLinkColumn

编辑 的默认设置DataGridView看起来像这样的行选择。请注意,在第二列的单元格改变其ForeColor白色而不是在第一列的单元格: enter image description here


我希望它在一个行选择看起来是这样的: enter image description here

回答

1

编辑当尝试远离单元格时,CellLeave事件将始终发生。

private void dataGridView1_SelectionChanged(object sender, EventArgs e) 
    { 
     foreach (DataGridViewLinkCell cell in 
      ((DataGridView) sender).SelectedCells.OfType<DataGridViewLinkCell>()) 
     { 
      if (cell.Selected) 
      { 
       cell.LinkColor = SystemColors.HighlightText; 
      } 
     } 

    } 

    private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e) 
    { 
     foreach (DataGridViewLinkCell cell in 
      ((DataGridView) sender).Rows[e.RowIndex].Cells.OfType<DataGridViewLinkCell>()) 
     { 
      cell.LinkColor = cell.LinkVisited ? Color.Purple : Color.Blue; 
     } 
    } 

Result

+0

请参阅我的 “编辑” 末作进一步澄清。 – nam 2014-09-01 18:46:42

+0

@nam请参阅我的**编辑**。 – 2014-09-02 21:14:33

+0

谢谢你试图帮助。这仍然不起作用。当选中一行(或第一列中的单元格)时,它仍会显示与我上面原始帖子的图1中相同的结果。我很惊讶 - 微软现在应该已经注意到,在选定的行(或该列上的单元格)上,链接列的奇怪默认着色格式。 – nam 2014-09-04 16:28:55

相关问题