如何实现ComboBox下拉列表显示图片

来源:互联网 发布:deepin linux 安装svn 编辑:程序博客网 时间:2024/05/17 22:50

 实现此功能主要通过ComboBox控件的DrawMode属性、DropDownStyle属性以及DrawItem事件和Graphic类的公共属性和方法完成。首先把DrawMode属性设置为OwnerDrawFixed,把DropDownStyle属性设置为DropDownList,然后在控件DrawItem事件下添加图片。主要代码如下:
private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox1.DrawItem+=new DrawItemEventHandler(comboBox1_DrawItem);
            comboBox1.Items.Add("123");
            comboBox1.Items.Add("456");
            comboBox1.Items.Add("789");
            for (int i = 0; i < comboBox1.Items.Count+1; i++)
            {
                imageList1.Images.Add(imageList1.Images[0]);
                //必须保证图片数大于等于选项数目
            }
        }


        private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            Graphics g = e.Graphics;
            Rectangle r = e.Bounds;
            Size imageSize = imageList1.Images[0].Size;

            if (e.Index >= 0)
            {
                Font fn = new Font("Tahoma", 10, FontStyle.Bold);
                string s = (string)comboBox1.Items[e.Index];
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Near;
                if (e.State == (DrawItemState.NoAccelerator | DrawItemState.NoFocusRect))
                {
                    //画条目背景
                    e.Graphics.FillRectangle(new SolidBrush(Color.Red), r);
                    //绘制图像
                    imageList1.Draw(e.Graphics, r.Left, r.Top, e.Index);
                    //显示字符串
                    e.Graphics.DrawString(s, fn, new SolidBrush(Color.Black), r.Left + imageSize.Width, r.Top);
                    //显示取得焦点时的虚线框
                    e.DrawFocusRectangle();
                }
                else
                {
                    e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue), r);
                    imageList1.Draw(e.Graphics, r.Left, r.Top, e.Index);
                    e.Graphics.DrawString(s, fn, new SolidBrush(Color.Black), r.Left + imageSize.Width, r.Top);
                    e.DrawFocusRectangle();
                }
            }
        }