C#:更改列表框项目颜色 [英] C# : change listbox items color

查看:16
本文介绍了C#:更改列表框项目颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 Windows 窗体上的程序我有一个列表框,我正在验证数据我希望将正确的数据添加到绿色的列表框中,而添加的无效数据使用红色,我还希望从列表框中自动添加项目时向下滚动并感谢

i am working on program on windows forms I have a listbox and I am validating data I want the correct data be added to the listbox with color green while the invalid data added with red color and I also want from the listbox to auto scroll down when an item is added and thanks

代码:

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

推荐答案

假设 WinForms,我会这样做:

Assuming WinForms, this is what I would do:

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

Start by making a class to contain the item to add to the listbox.

public class MyListBoxItem {
    public MyListBoxItem(Color c, string m) { 
        ItemColor = c; 
        Message = m;
    }
    public Color ItemColor { get; set; }
    public string Message { get; set; }
}

使用此代码将项目添加到您的列表框:

Add items to your listbox using this code:

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 事件创建一个事件处理程序.这使您可以随心所欲地绘制每个项目.

In the properties of the ListBox, set DrawMode to OwnerDrawFixed, and create an event handler for the DrawItem event. This allows you to draw each item however you wish.

在 DrawItem 事件中:

In the DrawItem Event:

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
    }
}

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

There are a few limitations - the main one being that you'd need to write your own click handler and redraw appropriate items to make them appear selected, since Windows won't do that in OwnerDraw mode. However, if this is just intended to be a log of things happening in your application, you may not care about items appearing selectable.

滚动到最后一项试试

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

这篇关于C#:更改列表框项目颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆