假设使用WinForms,这是我会做的事情:
首先创建一个类来包含要添加到列表框中的项。
public class MyListBoxItem {
public MyListBoxItem(Color c, string m) {
ItemColor = c;
Message = m;
}
public Color ItemColor { get; set; }
public string Message { get; set; }
}
使用以下代码向列表框中添加项目:
listBox1.Items.Add(new MyListBoxItem(Colors.Green, "Validated data successfully"));
listBox1.Items.Add(new MyListBoxItem(Colors.Red, "Failed to validate data"));
在ListBox的属性中,将DrawMode设置为OwnerDrawFixed,并创建一个DrawItem事件处理程序。这样可以按照您的意愿绘制每个项目。
在DrawItem事件中:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem;
if (item != null)
{
e.Graphics.DrawString(
item.Message,
listBox1.Font,
new SolidBrush(item.ItemColor),
0,
e.Index * listBox1.ItemHeight
);
}
else
{
}
}
有一些限制 - 主要是因为在OwnerDraw模式下,您需要编写自己的单击处理程序并重新绘制适当的项目以使它们显示为已选择状态,因为Windows不会执行此操作。 但是,如果这只是您的应用程序中发生事情的记录,您可能不关心项目是否可选择。
要滚动到最后一个项目,请尝试
listBox1.TopIndex = listBox1.Items.Count - 1;