我需要更改列表框中所选项目的背景颜色。你能给我一些代码示例吗?我已经尝试添加DrawItem事件,但它对我没有用。
答案 0 :(得分:1)
将列表框的DrawMode
设置为OwnerDrawFixed
。
然后分配这些事件:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
int index = e.Index;
Graphics g = e.Graphics;
foreach (int selectedIndex in this.listBox1.SelectedIndices)
{
if (index == selectedIndex)
{
// Draw the new background colour
e.DrawBackground();
g.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
}
}
// Get the item details
Font font = listBox1.Font;
Color colour = listBox1.ForeColor;
string text = listBox1.Items[index].ToString();
// Print the text
g.DrawString(text, font, new SolidBrush(Color.Black), (float)e.Bounds.X, (float)e.Bounds.Y);
e.DrawFocusRectangle();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Invalidate();
}