How to color lines in a listbox?
Hy! I would like display my log system开发者_StackOverflow output on a listbox, with custom highlighting depending on the level or log entry. (General, warning, error, debug, trace)
somelistbox.Items.Add("Starting"); // I would like to drawn this as grey
somelistbox.Items.Add("Error!"); // I would like to drawn this as red
So I would like to add a new thing, like typeoflog, but I dont know how to do it.
somelistbox.Items.Add("Error!",Type.Error);
I've got this code, which colors items , depends on item number, but Thats not what I'm looking for.
private void general_log_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Brush myBrush = Brushes.Black;
switch (actualLogType)
{
case LogTypes.General:
myBrush = Brushes.Black;
break;
case LogTypes.Warning:
myBrush = Brushes.Orange;
break;
case LogTypes.Error:
myBrush = Brushes.Purple;
break;
case LogTypes.Debug:
myBrush = Brushes.AntiqueWhite;
break;
}
e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
UPDATE : If anyone still looking into this, I'ld suggest to take a look at the NLog project. It has colored richtextbox target.
A ListBox can store more than just strings, it can also store objects. You want to take advantage of that here, the list item in your case has more state than just the text. Add a little nested helper class:
private enum itemType { error, warning }
private class listObject {
public listObject(string txt, itemType type) { Text = txt; Type = type; }
public string Text;
public itemType Type;
public override string ToString() { return Text; }
}
Note how the ToString() override generates the text that the user sees. Now just add items to the listbox like this:
listBox1.Items.Add(new listObject("blah", itemType.warning));
And cast the object back to your class in the DrawItem event handler:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e) {
var obj = listBox1.Items[e.Index] as listObject;
// etc..
}
And use obj.Type to determine colors.
If it is not WPF listbox, you need to use Win32 API. Is that what you are after?
UPDATE
Using WIn32 API is not necessary: http://www.codeproject.com/KB/combobox/ColorListBoxIcons.aspx
You could also use a ListView instead of ListBox, so you could access its BackColor property:
listView1.Items[i].BackColor = Color.Black;
精彩评论