2016/09/06

C#.Net 自訂ListBox文字顏色

ListBox.DrawMode要改成DrawMode.OwnerDrawFixed

程式碼:
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {

        /// <summary>
        /// Odd
        /// </summary>
        private readonly SolidBrush BRUSH_GRAY = new SolidBrush(Color.Gray);

        /// <summary>
        /// even
        /// </summary>
        private readonly SolidBrush BRUSH_BLUE = new SolidBrush(Color.Blue);

        public Form1()
        {
            InitializeComponent();

            //自行繪製
            listBox1.DrawMode = DrawMode.OwnerDrawFixed;

            foreach (var n in Enumerable.Range(1, 50))
            {
                listBox1.Items.Add(n);
            }

            listBox1.DrawItem += (s, e) =>
            {
                if (e.Index < 0)
                    return;

                var brushRect = new SolidBrush(Color.White);
                e.Graphics.FillRectangle(brushRect, e.Bounds);

                var str = listBox1.Items[e.Index].ToString();
                var number = Convert.ToInt16(str);
                var brush = (number % 2 != 0) ? BRUSH_GRAY : BRUSH_BLUE;
                e.Graphics.DrawString(str, Font, brush, e.Bounds);
                e.DrawFocusRectangle();
            };
        }

    }
}

執行結果: