【发布时间】:2012-03-21 10:51:24
【问题描述】:
我使用ListBox 插入诸如You add Michael in your database、You 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"));
此代码有效,但是当我插入多个项目时,滚动无法正常工作 - 文本不会出现。我究竟做错了什么?或者有其他方法吗?
【问题讨论】: