2010-06-25 50 views
0

我有一些代码来改变列表框的行为。我可以改变文字的颜色,但我无法改变每行背景的颜色。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

+1

我会检查,以确保你正在做一个正确的比较LBLines [h]!=“无”第一个' – 2010-06-25 15:26:05

回答

3

硬而不在你的代码(循环,方法,...)更多方面的说法,但是这个代码做什么,我想这是你想要的:

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); 
    } 
} 

注意,ListBoxDrawStyle属性设置为OwnerDrawFixed

+0

是的,我删除循环,但它没有修复的东西。 – Wildhorn 2010-06-25 15:52:44

+0

当字符串为“None”时,您可能还想要执行e.DrawBackground()... – 2010-06-25 16:01:30

+0

不,看起来背景对所有行都是如此。这很奇怪,因为DrawString工作得很好。 – Wildhorn 2010-06-25 17:13:19