【问题标题】:ListBox insert items in colorListBox 以颜色插入项目
【发布时间】:2012-03-21 10:51:24
【问题描述】:

我使用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"));

此代码有效,但是当我插入多个项目时,滚动无法正常工作 - 文本不会出现。我究竟做错了什么?或者有其他方法吗?

【问题讨论】:

    标签: c# winforms listbox


    【解决方案1】:

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

    【讨论】:

    • 是的,我做到了。在ListView 中非常简单。如果可能的话,这更像是实验
    【解决方案2】:

    你应该使用:

    e.Bounds.Top
    

    代替:

    e.Index * listBox1.ItemHeight
    

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

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

    并且您应该正确处理您为绘制文本而创建的画笔。

    【讨论】:

      【解决方案3】:

      把图纸改成

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-31
        • 1970-01-01
        • 1970-01-01
        • 2015-08-08
        • 2012-08-21
        • 1970-01-01
        • 2011-10-26
        相关资源
        最近更新 更多