【问题标题】:how to change BackColor/ForeColor of a single cell in ObjectListView如何更改 ObjectListView 中单个单元格的 BackColor/ForeColor
【发布时间】:2020-04-28 06:23:49
【问题描述】:

我正在尝试在ObjectListView 中设置单元格的前景色。 SO和其他网站上有关于这个的问题和答案,建议使用ObjectListViewFormatCell事件。如http://objectlistview.sourceforge.net/cs/recipes.html#how-can-i-change-the-colours-of-a-row-or-just-a-cell中所述

我尝试了代码并且它可以工作,但是当需要重绘单元格时它可以工作(它们最初显示为黑色,并且每个项目我将鼠标移到它上面调用事件)。但我真的不需要一个事件,因为我想设置一个固定的颜色,比如:

 foreach (OLVListItem item in olv.Items)
      if (item.SubItems[7].Text != "")
      {
          if (item.SubItems[7].Text.StartsWith("-"))
              item.SubItems[7].ForeColor = Color.Red;
          else item.SubItems[7].ForeColor = Color.DarkGreen;
      }

但上面的代码不影响结果。

【问题讨论】:

    标签: c# objectlistview


    【解决方案1】:

    我无意中通过它的属性找到了答案。我将此添加为答案,以便它可以帮助其他人。 OLVListItem 有一个属性UseItemStyleForSubItems,默认情况下是true,它使用与ObjectListView 相同的字体、前景色和背景色作为其项目。将其值设置为 false 有效:

    foreach (OLVListItem item in olv.Items)
          if (item.SubItems[7].Text != "")
          {
             item.UseItemStyleForSubItems = false;
              if (item.SubItems[7].Text.StartsWith("-"))
                  item.SubItems[7].ForeColor = Color.Red;
              else item.SubItems[7].ForeColor = Color.DarkGreen;
          }
    

    【讨论】:

    • 我不明白为什么使用 FormatCell 对您不起作用,如问题中所述。这个解决方案很脏,因为当列顺序改变时它会中断,并且它不使用实际的模型对象来检查使用 OLV 时不鼓励的条件。
    猜你喜欢
    • 2015-12-21
    • 2015-12-01
    • 2021-04-10
    • 2016-11-09
    • 2020-02-09
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多