【问题标题】:C# Listview - How to change the color of each new item?C# Listview - 如何更改每个新项目的颜色?
【发布时间】:2017-12-05 01:50:38
【问题描述】:

我从Button 的点击事件将项目添加到ListView 控件。我希望每个 项目都被涂成 红色 项目被涂成 白色 (所以只添加了最新的项目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;
    }
}

我怎样才能只将最新添加的项目涂成红色?

【问题讨论】:

  • 该代码如何区分新项目和旧项目?它只是交替。
  • @Plutonix 是的,这是我的问题。我想为最新添加的项目着色。谢谢。
  • 您使用的是 Windows 窗体还是 WPF?
  • @mageos 我正在使用 Windows 窗体。
  • 为什么不显示添加项目的代码?那不是你要设置颜色的地方吗?

标签: c# winforms listview


【解决方案1】:

添加一个新方法以将项目添加到您的 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
}

【讨论】:

    【解决方案2】:
        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();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-06
      • 2012-07-01
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 2015-01-07
      • 2015-12-06
      • 1970-01-01
      相关资源
      最近更新 更多