Я использую 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"));
Этот код работает, но когда я вставляю несколько элементов, прокрутка не работает правильно - текст не отображается.Что я делаю неправильно?Или есть другой способ сделать это?