列表框项目颜色错误
本文关键字:错误 颜色 项目 列表 | 更新日期: 2023-09-27 18:24:17
我想给每组文件名一个不同的颜色,但是在该代码中只有第一个文件名将具有不同的颜色,调试代码时,我找不到任何错误,问题出在哪里?。。。
public class ListBoxEx : ListBox
{
private string PreviousText = string.Empty;
private string CurrentText = string.Empty;
private bool equal = false;
public ListBoxEx()
{
this.DrawMode = DrawMode.OwnerDrawFixed;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
try
{
e.DrawBackground();
if (this.Items.Count > 0 && e.Index > 0)
{
PreviousText = Path.GetFileName(this.Items[e.Index - 1].ToString());
CurrentText = Path.GetFileName(this.Items[e.Index].ToString());
if (CurrentText == PreviousText)
equal = true;
else equal = false;
if (equal)
e.Graphics.FillRectangle(new SolidBrush(Color.LightYellow), e.Bounds);
else
e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue), e.Bounds);
e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));
base.OnDrawItem(e);
}
}
catch (Exception ex)
{
throw (ex);
}
}
}
找到了,
string tempFilename = string.Empty;
SolidBrush Brushcolor;
bool colorSwitch = false;
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.DrawBackground();
// Group colors
string text = this.Items[e.Index].ToString();
string filename = Path.GetFileName(text);
if (filename == tempFilename)
equal = true;
else equal = false;
if (equal)
Brushcolor = ExChangeBrush(!colorSwitch);
else
{
Brushcolor = ExChangeBrush(colorSwitch);
colorSwitch = !colorSwitch;
}
tempFilename = filename;
// end Group colors
e.Graphics.FillRectangle(Brushcolor, e.Bounds);
e.Graphics.DrawString(text, e.Font, new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));
base.OnDrawItem(e);
}