winforms C# Listview不同颜色的行和列

jtjikinw  于 2022-12-30  发布在  C#
关注(0)|答案(1)|浏览(336)

我尝试在列表视图中添加不同颜色的行和列。
I want to like this
it is the first listview
首先我使用这些代码

foreach (ListViewItem item in listView.Items)
{
   item.BackColor = item.Index % 2 == 0 ? Color.FromArgb(70, 70, 70) : Color.FromArgb(61, 61, 61);
}

Then the listview shown like this
然后我试了这些密码

foreach (ListViewItem item in listView.Items)
{
   item.SubItems[2].BackColor = Color.FromArgb(18, 64, 100);
   item.SubItems[9].BackColor = Color.FromArgb(105, 16, 38);
   item.UseItemStyleForSubItems = false;
}

Ande last listview shown like this
怎么了?
谢谢您。

xkftehaa

xkftehaa1#

当您应用交替行颜色时,您只将其应用于列1(也称为item)。当您应用列[2和9]格式时,您关闭UseItemStyleForSubItems,因此现在只有第一列具有交替行颜色。您必须将交替行和列格式设置代码合并到一个代码块中,如下所示:

foreach (ListViewItem item in listView.Items)
{
    //Disable item styles for sub items so we can apply column colors.
    item.UseItemStyleForSubItems = false;

    //Create the main colors used for row formatting.
    Color a = Color.FromArgb(61, 61, 61);
    Color b = Color.FromArgb(70, 70, 70);

    //Create the alternate colors used for column 2 and 9.
    Color alt2 = Color.FromArgb(18, 64, 100);
    Color alt9 = Color.FromArgb(105, 16, 38);

    //Apply colors to column 1
    if (item.Index % 2 == 0) {
        item.BackColor = b;
    } else {
        item.BackColor = a;
    }
    
    //Loop through the sub items and apply colors.
    foreach(ListViewSubItem sub in item.SubItems) {
        if (sub.Index == 2) {             //Apply column 2 color.
            sub.BackColor = alt2;
        } else if (sub.Index == 9) {      //Apply column 9 color.
            sub.BackColor = alt9;         
        } else if (item.Index % 2 == 0) { //Apply alt row color.
            sub.BackColor = b;            
        } else {                          //Apply main row color. This is the default.
            sub.BackColor = a;            
        }
    }
}

相关问题