C#:更改列表框项目颜色

18
我正在开发一个 Windows Forms 程序,其中包含一个列表框。我正在验证数据,并希望将正确的数据以绿色添加到列表框中,而将无效的数据以红色添加。当添加项目时,我还希望列表框自动向下滚动。谢谢。
代码:
try
{
    validatedata;
    listBox1.Items.Add("Successfully validated the data  : "+validateddata);
}
catch()
{
    listBox1.Items.Add("Failed to validate data: " +validateddata);
}

8
你忘记了实际上要“提出一个问题”。 - jv42
  1. 仔细阅读你的问题,并接受那些对你有帮助或正确的答案。
  2. 指明问题和技术 (WinForms,WPF...)。
- Tigran
你忘了提到WinForms/WPF/WebForms/... - H H
更正了问题,Windows表单 - BOSS
3个回答

39
假设使用WinForms,这是我会做的事情:
首先创建一个类来包含要添加到列表框中的项。
public class MyListBoxItem {
    public MyListBoxItem(Color c, string m) { 
        ItemColor = c; 
        Message = m;
    }
    public Color ItemColor { get; set; }
    public string Message { get; set; }
}

使用以下代码向列表框中添加项目:
listBox1.Items.Add(new MyListBoxItem(Colors.Green, "Validated data successfully"));
listBox1.Items.Add(new MyListBoxItem(Colors.Red, "Failed to validate data"));

在ListBox的属性中,将DrawMode设置为OwnerDrawFixed,并创建一个DrawItem事件处理程序。这样可以按照您的意愿绘制每个项目。
在DrawItem事件中:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
    if (item != null) 
    {
        e.Graphics.DrawString( // Draw the appropriate text in the ListBox
            item.Message, // The message linked to the item
            listBox1.Font, // Take the font from the listbox
            new SolidBrush(item.ItemColor), // Set the color 
            0, // X pixel coordinate
            e.Index * listBox1.ItemHeight // Y pixel coordinate.  Multiply the index by the ItemHeight defined in the listbox.
        );
    }
    else 
    {
         // The item isn't a MyListBoxItem, do something about it
    }
}

有一些限制 - 主要是因为在OwnerDraw模式下,您需要编写自己的单击处理程序并重新绘制适当的项目以使它们显示为已选择状态,因为Windows不会执行此操作。 但是,如果这只是您的应用程序中发生事情的记录,您可能不关心项目是否可选择。

要滚动到最后一个项目,请尝试

listBox1.TopIndex = listBox1.Items.Count - 1;

4
有更好的方法来实现DrawItem处理程序 - 参见https://dev59.com/7EvSa4cB1Zd3GeqPiv3_#2268234。 - splintor
4
你忘记添加了:this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;。需要加上这行代码,才能实现自定义绘制ListBox的功能。请注意不要改变原意,使翻译易于理解。 - Liran Friedman
看起来不错。为了简化代码,可以使用 e.Font 替代 listBox1.Font,并将最后两个参数(X 和 Y 坐标)替换为一个参数:e.Bounds - Rufus L
在您的代码中添加 "using System.Drawing;" 以使用 "Color"。 - Onsightfree

2

虽然这不是你问题的回答,但你可能想看一下 ObjectListView。它是一个 ListView 而不是 ListBox,但非常灵活且易于使用。可以使用单个列来表示你的数据。

我使用它为每一行着色状态。

http://objectlistview.sourceforge.net/cs/index.html

当然,这是针对 WinForms 的。


0

怎么样?

            MyLB is a listbox

            Label ll = new Label();
            ll.Width = MyLB.Width;
            ll.Content = ss;
            if(///<some condition>///)
                ll.Background = Brushes.LightGreen;
            else
                ll.Background = Brushes.LightPink;
            MyLB.Items.Add(ll);

这是一个很好的想法,但该死的我无法让它工作。ListBox只显示第一项 :-(。 - JonP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接