C#Listbox.DrawItem为每行着色
问题描述:
我有一些代码来改变列表框的行为。我可以改变文字的颜色,但我无法改变每行背景的颜色。C#Listbox.DrawItem为每行着色
这是一个循环,每我行
LBLines是串店在一个全局变量
if (LBLines[e.Index] != "None")
{
e.Graphics.FillRectangle(new SolidBrush(Color.FromName(LBLines[e.Index])),
e.Bounds.X,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height);
}
这将颜色相同的颜色的每一个线的阵列,即使是那些上市作为“无”,你需要的是他们保持与默认背景颜色相同的颜色。
编辑:比较不是问题,问题来自e.Graphics.FillRectangle。无论我正在绘制的是什么,它似乎都会为所有行空格着色。
EDIT2:修改后的代码表明h后等于e.Index
答
硬而不在你的代码(循环,方法,...)更多方面的说法,但是这个代码做什么,我想这是你想要的:
public partial class Form1 : Form
{
string[] Colors { get; set; }
public Form1()
{
InitializeComponent();
Colors = new string[] { "red", "blue", "white", "none", "orange" };
listBox1.Items.AddRange(Colors);
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
if (Colors[e.Index] != "none")
{
using (var brush = new SolidBrush(Color.FromName(Colors[e.Index])))
{
e.Graphics.FillRectangle(brush, e.Bounds);
}
}
e.Graphics.DrawString(Colors[e.Index], Font, SystemBrushes.ControlText, e.Bounds);
}
}
注意,ListBox
的DrawStyle
属性设置为OwnerDrawFixed
。
我会检查,以确保你正在做一个正确的比较LBLines [h]!=“无”第一个' – 2010-06-25 15:26:05