Skip to main content
 首页 » 编程设计

C# Winforms ListBox 项目满足条件时设置背景色

2024年02月13日13tuyile006

我有一个集合,它是列表框的数据源。 我想枚举 ListBox 项并在集合项具有特定属性时更改 BackColor。 for 中的代码根本不起作用,我迷路了。 如果相应的类别具有特定 ID,我将如何更改背景颜色?

  categorien.Add(new Categorie() { ID = 0, Naam = "Blond" }); 
  categorien.Add(new Categorie() { ID = 1, Naam = "Donker" }); 
  listBox1.DataSource = categorien; 
  listBox1.DisplayMember = "Naam"; 
  listBox1.ValueMember = "ID"; 
 
  for (int i = 0; i < listBox1.Items.Count; i++ ) { 
    if (categorien.ID == someID) { 
      listBox1.Items[i].BackColor = Color.Gray; 
    } 
  } 

请您参考如下方法:

试试下面

private void listBox1_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    var category = listBox1.Items[e.Index] as Categorie; 
    Color backColor = Color.Green; 
    if (category.ID == someID) 
    { 
        backColor = Color.Gray; 
    } 
 
    // draw back color and text  
}