C#Listview - 如何更改每个新项目的颜色?

时间:2017-12-05 01:50:39

标签: c# winforms listview

我从ListView的点击事件向Button控件添加项目。我希望每个项目的颜色为红色,而项目的颜色为白色(因此仅添加了最新项目) ListView的颜色为红色。

我做了类似的事情,但它只交替红色和白色之间的颜色:

for (int i = 0; i <= listView1.Items.Count - 1; i++)
{
    if (listView1.Items[i].Index % 2 == 0)
    {
        listView1.Items[i].BackColor = Color.Red;
    }
    else
    {
        listView1.Items[i].BackColor = Color.White;
    }
}

如何才能将最新添加的项目涂成红色?

2 个答案:

答案 0 :(得分:3)

添加一个新方法,将项目添加到listView:

public void AddNewItemToListBox(string text)
{
  // Make existing background white      
  for (int i = 0; i <= listView1.Items.Count - 1; i++)
  {
    listView1.Items[i].BackColor = Color.White;
  }
  // New one with red background
  ListViewItem lvi = new ListViewItem(); 
  lvi.Text = text;
  lvi.BackColor = Color.Red;
  lv.Items.Add(lvi); // lv is your listview
}

答案 1 :(得分:0)

    private void listView_DrawItem(object sender, DrawListViewItemEventArgs e)
    {
        if (e.ItemIndex != (listView.Items.Count - 1))
        {
            // Draw the background and focus rectangle for a selected item.
        }
        else
        {
            // Draw the background for an unselected item.
            using (LinearGradientBrush brush =new LinearGradientBrush(e.Bounds, Color.Red, Color.Red, LinearGradientMode.Horizontal))
            {
                e.Graphics.FillRectangle(brush, e.Bounds);
            }
        }

        // Draw the item text for views other than the Details view.
        if (listView.View != View.Details)
        {
            e.DrawText();
        }
    }