Предполагая, что 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; // 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
}
}
Существует несколько ограничений - главное из них заключается в том, что вам нужно написать собственный обработчик кликов и перерисовать соответствующие элементы, чтобы они выглядели выделенными, поскольку Windows не будет делать это в режиме OwnerDraw. Однако, если это всего лишь журнал событий, происходящих в вашем приложении, вас могут не волновать элементы, которые можно выбрать.
Чтобы перейти к последнему пункту, попробуйте
listBox1.TopIndex = listBox1.Items.Count - 1;