C# 列表框以彩色插入项目
我使用C# 列表框以彩色插入项目,c#,winforms,listbox,C#,Winforms,Listbox,我使用ListBox插入文本,如在数据库中添加Michael,删除Michael listBox1.Items.Insert(0,"You add " + name + " in your database\n"); 它工作正常。如何将颜色设置为一次黑色(用于插入)和一次红色(用于删除)?我试过这个: public class MyListBoxItem { public MyListBoxItem(Color c, string m) {
ListBox
插入文本,如在数据库中添加Michael
,删除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无法正常工作-文本不会出现。我做错了什么?或者还有其他方法吗?您是否考虑过在报表视图中使用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);
是的。在
列表视图中
非常简单。如果可能的话,这更像是实验