listBox 增加圖標,現在使用DrawItem 的事件自己繪制圖標及文字,繪制完成后需要做list內容的選擇效果
listBox 的 DrawMode 需要設置 DrawMode.OwnerDrawFixed, 否則不會寫顯示效果
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace EXchangeDatum { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.Load += Form1_Load; listBox1.DrawItem += ListBox1_DrawItem; } private void ListBox1_DrawItem(object sender, DrawItemEventArgs e) { Brush myBrush = Brushes.Black; Color RowBackColorSel = Color.FromArgb(150, 200, 250);//選擇項目顏色 if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { myBrush = new SolidBrush(RowBackColorSel); } else { myBrush = new SolidBrush(Color.White); } e.Graphics.FillRectangle(myBrush, e.Bounds); e.DrawFocusRectangle();//焦點框 //繪制圖標 Image image = imageList1.Images[e.Index]; Graphics graphics = e.Graphics; Rectangle bound = e.Bounds; Rectangle imgRec = new Rectangle( bound.X, bound.Y, bound.Height, bound.Height); Rectangle textRec = new Rectangle( imgRec.Right, bound.Y, bound.Width - imgRec.Right, bound.Height); if (image != null) { e.Graphics.DrawImage( image, imgRec, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel); //繪制字體 StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Near; e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), textRec, stringFormat); } } private void Form1_Load(object sender, EventArgs e) { listBox1.DrawMode = DrawMode.OwnerDrawFixed; listBox1.Items.Add("大白菜"); listBox1.Items.Add("西藍花"); listBox1.Items.Add("花菜"); listBox1.Items.Add("芹菜"); listBox1.Items.Add("胡蘿卜"); listBox1.Items.Add("辣椒"); listBox1.Items.Add("西紅柿"); } } }