日期:2014-05-18  浏览次数:20811 次

窗体程序listbox改变颜色
我要改变listbox 中的item颜色 ,要做的效果是 开始加载的是默认黑色,点击按钮后item 改变颜色
我现在只能是 单机按钮后,必须fouce 一下listbox 才能变色
C# code

      private void button1_Click(object sender, EventArgs e)
        {
            listBox1.DrawItem+= new System.Windows.Forms.DrawItemEventHandler(DrawItemHandler);
            listBox1.Update();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add("aaa");

        }

        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("aaa");
            listBox1.Items.Add("aaa");
            listBox1.Items.Add("aaa");

            listBox1.Items.Add("aaa");
            listBox1.Items.Add("aaa");

        }
        private void DrawItemHandler(object sender, System.Windows.Forms.DrawItemEventArgs e)
        {
            // Set the DrawMode property to draw fixed sized items.
            listBox1.DrawMode = DrawMode.OwnerDrawVariable;
            // Draw the background of the ListBox control for each item.
            e.DrawBackground();
            e.DrawFocusRectangle();
            // Define the default color of the brush as black.
            Brush myBrush = Brushes.Orange;

            switch (e.Index)
            {
                case 0:
                    myBrush = Brushes.Red;
                    break;
                case 1:
                    myBrush = Brushes.Orange;
                    break;
                case 2:
                    myBrush = Brushes.Purple;
                    break;
            }

            // Draw the current item text based on the current Font and the custom brush settings.
            e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
          
            
        }



------解决方案--------------------
listBox1.Invalidate();