代码之家  ›  专栏  ›  技术社区  ›  Wildhorn

C#Listbox.DrawItem为每条线上色

  •  0
  • Wildhorn  · 技术社区  · 15 年前

    我有一些代码来改变listbox的行为。我可以改变文本的颜色,但我不能改变每行背景的颜色。

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

    这将颜色相同的每一行,甚至那些列为“无”,我需要的是,他们保持相同的颜色作为默认背景色。

    EDIT2:修改代码以显示h等于e.Index

    1 回复  |  直到 15 年前
        1
  •  3
  •   Tor Livar    15 年前

    如果代码周围没有更多的上下文(循环、方法等),很难说,但是这段代码实现了我认为您想要的:

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

    DrawStyle 财产 ListBox OwnerDrawFixed .