在颜色列表框插入项目 [英] ListBox insert items in color

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

问题描述

我使用 ListBox 插入文本,例如您在数据库中添加Michael 删除Michael ,...

I use ListBox for inserting text like You add Michael in your database, You delete Michael, ...

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

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

It works ok. How can i set color once black (for insert) and once red (for deletion)? I tried with this:

 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不能正常工作 - 文本不会出现。我做错了什么?

This code works, but when i insert multiple items, scrol doesn't work correctly - text does not appear. What am i doing wrong? Or is any other way to do this?

推荐答案

应该使用:

e.Bounds.Top

/ p>

instead of:

e.Index * listBox1.ItemHeight

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

Also, before drawing the text, I recommend drawing the background so you can see which item is selected, if the list supports selection, or support the list's desired item background color in any case:

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

你应该正确处理你创建的Brush来绘制文本。

And you should properly dispose of the Brush that you're creating to draw the text.

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

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