ListBox以彩色插入项目

本文关键字:插入项目 彩色 ListBox | 更新日期: 2023-09-27 18:28:34

我使用ListBox插入文本,如You add Michael in your databaseYou delete Michael。。。

 listBox1.Items.Insert(0,"You add " + name + " in your database'n");

它工作正常。我如何设置颜色一次黑色(插入)和一次红色(删除)?我试过这个:

 public class MyListBoxItem
    {
        public MyListBoxItem(Color c, string m)
        {
            ItemColor = c;
            Message = m;
        }
        public Color ItemColor { get; set; }
        public string Message { get; set; }
    }
    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
        }
    }

插入时:

 listBox1.Items.Insert(0, new MyListBoxItem(Color.Black, "You add " + name + " in your database'n"));
 listBox1.Items.Insert(0, new MyListBoxItem(Color.Red, "You delete " + name + "'n"));

这段代码有效,但当我插入多个项目时,scrol无法正常工作——文本不会出现。我做错了什么?或者有其他方法吗?

ListBox以彩色插入项目

您是否考虑过在报表视图中使用ListView而不是listbox?这样就不必为了获得颜色而自定义图形。

您应该使用:

e.Bounds.Top

而不是:

e.Index * listBox1.ItemHeight

此外,在绘制文本之前,我建议绘制背景,这样你就可以看到选择了哪个项目,如果列表支持选择,或者在任何情况下都支持列表所需的项目背景颜色:

using (Brush fill = new SolidBrush(e.BackColor))
{
   e.Graphics.FillRectangle(fill, e.Bounds);
}

你应该正确地处理你正在创建的画笔来绘制文本。

将绘图更改为

 e.Graphics.DrawString(item.Message, 
   listBox1.Font, 
   new SolidBrush(item.ItemColor), 
   0,
   e.Bounds.Top);