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

BOS*_*OSS 15 c# listbox colors winforms

我正在研究Windows窗体上的程序我有一个列表框,我正在验证数据我希望将正确的数据添加到列表框中,颜色为绿色,而无效数据添加了红色,我也希望从列表框中自动向下滚动添加了一个项目,谢谢

代码:

try
{
    validatedata;
    listBox1.Items.Add("Successfully validated the data  : "+validateddata);
}
catch()
{
    listBox1.Items.Add("Failed to validate data: " +validateddata);
}
Run Code Online (Sandbox Code Playgroud)

Nei*_*eil 34

假设WinForms,这就是我要做的:

首先创建一个类来包含要添加到列表框的项目.

public class MyListBoxItem {
    public MyListBoxItem(Color c, string m) { 
        ItemColor = c; 
        Message = m;
    }
    public Color ItemColor { get; set; }
    public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

使用以下代码将项添加到列表框:

listBox1.Items.Add(new MyListBoxItem(Colors.Green, "Validated data successfully"));
listBox1.Items.Add(new MyListBoxItem(Colors.Red, "Failed to validate data"));
Run Code Online (Sandbox Code Playgroud)

在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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

listBox1.TopIndex = listBox1.Items.Count - 1;
Run Code Online (Sandbox Code Playgroud)

  • 有更好的方法来实现DrawItem处理程序 - 请参阅http://stackoverflow.com/a/2268234/46635. (4认同)
  • 你忘了添加:`this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;` (4认同)