C# Winform编程ListBox之添加图标
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("西红柿"); } } }