C#:更改列表框项目颜色
我正在研究Windows窗体上的程序我有一个列表框,我正在validation数据我希望将正确的数据添加到列表框中,颜色为绿色,而无效数据添加了红色,我也希望从列表框中自动向下滚动添加了一个项目,谢谢
代码:
try { validatedata; listBox1.Items.Add("Successfully validated the data : "+validateddata); } catch() { listBox1.Items.Add("Failed to validate data: " +validateddata); }
假设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;
不是你的问题的答案,但你可能想看看ObjectListView。 它是ListView而不是列表框,但它非常灵活且易于使用。 它可以与单个列一起使用来表示您的数据
我用它来为每一行的状态着色
http://objectlistview.sourceforge.net/cs/index.html
这当然适用于WinForms。
怎么样
MyLB is a listbox Label ll = new Label(); ll.Width = MyLB.Width; ll.Content = ss; if(//////) ll.Background = Brushes.LightGreen; else ll.Background = Brushes.LightPink; MyLB.Items.Add(ll);