如何在ObjectListView中更改单个单元格的BackColor/ForeColor



我正在尝试在ObjectListView中设置单元格的ForeColor。SO等网站对此存在疑问和解答,建议使用ObjectListViewFormatCell事件。如中所述http://objectlistview.sourceforge.net/cs/recipes.html#how-可以改变一行或一个细胞的颜色

我尝试了一下代码,它很有效,但当需要重新绘制单元格时,它也很有效(它们一开始看起来是黑色的,每次我将鼠标移到它上面时,就会调用事件(。但我并不真的需要一个事件,因为我想设置一个固定的颜色,比如:

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;
}

但是上面的代码并没有影响结果。

我意外地通过它的属性找到了答案。我添加这个作为答案,这样它可以帮助其他人。OLVListItem有一个属性UseItemStyleForSubItems,默认情况下是true,它对其项使用与ObjectListView相同的Font、ForeColor和BackColor。将其值设置为false worked:

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;
}

最新更新