我正在尝试在列表框中插入项目,但我想根据整数为特定项目的文本着色。如何在列表框中插入具有特定颜色的项目?
谢谢!
答案 0 :(得分:1)
将DrawMode设置为Listbox控件的OwnerDrawFixed。并将listBox_DrawItem事件处理程序关联到它listbox draw item
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Graphics yourObj = e.Graphics;
yourObj .FillRectangle(new SolidBrush(Color.Red), e.Bounds);
e.DrawFocusRectangle();
}
答案 1 :(得分:1)
ListBox
项可以是任何类型的对象。这意味着您无法在添加ListBox项时为其设置颜色。
您需要DrawItem
事件。
ListBox.DrawItem事件在所有者绘制的ListBox的可视方面发生更改时发生。
private void lstBox_DrawItem(object sender, _
System.Windows.Forms.DrawItemEventArgs e)
{
//
// Draw the background of the ListBox control for each item.
// Create a new Brush and initialize to a Black colored brush
// by default.
//
e.DrawBackground();
Brush myBrush = Brushes.Black;
//
// Determine the color of the brush to draw each item based on
// the index of the item to draw.
//
switch (e.Index)
{
case 0:
myBrush = Brushes.Red;
break;
case 1:
myBrush = Brushes.Orange;
break;
case 2:
myBrush = Brushes.Purple;
break;
}
//
// Draw the current item text based on the current
// Font and the custom brush settings.
//
e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
e.Font, myBrush,e.Bounds,StringFormat.GenericDefault);
//
// If the ListBox has focus, draw a focus rectangle
// around the selected item.
//
e.DrawFocusRectangle();
}
答案 2 :(得分:0)
也许这段代码会给你一些想法......
listView1.Items.Clear();
int k = 0;
foreach (Player p in players)
{
ListViewItem lvitem = new ListViewItem();
lvitem.Text = p.name;
lvitem.BackColor = p.color;
listView1.Items.Add(lvitem);
k++;
}
玩家是班级。它有名字和颜色。