zoukankan      html  css  js  c++  java
  • c# comboBox输出图文效果

    核心代码:重写DrawItem事件

    void Event_CboDrawItem(object sender, DrawItemEventArgs e)
    {
        if (e.Index < 0) return;
        var cbo = sender as ComboBox;
        if (cbo == null) return;
    
        Graphics g = e.Graphics;
        System.Drawing.Rectangle r = e.Bounds;
        ImageList tmpImg = null;
        if (cbo == cboOriginLang) tmpImg = imgLstOrigin;
        else tmpImg = imgLstTarget;
        Size imageSize = tmpImg.ImageSize;
    
        Font fn = cbo.Font;
        var s = (KeyValuePair<string, string>)cbo.Items[e.Index];//这里要求外面给cbo赋值时绑定List<KeyValuePair<string, string>>
        StringFormat sf = new StringFormat();
        sf.Alignment = StringAlignment.Near;
        if (e.State == (DrawItemState.NoAccelerator | DrawItemState.NoFocusRect))
        {
            //画条目背景 
            e.Graphics.FillRectangle(new SolidBrush(Color.White), r);//没有选中时背景为白色
            //绘制图像 
            tmpImg.Draw(e.Graphics, r.Left, r.Top, e.Index);
            //显示字符串 
            e.Graphics.DrawString(s.Value, fn, new SolidBrush(Color.Black), r.Left + imageSize.Width, r.Top);
            //显示取得焦点时的虚线框 
            e.DrawFocusRectangle();
        }
        else
        {
            e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue), r);//选中背景为浅灰
            tmpImg.Draw(e.Graphics, r.Left, r.Top, e.Index);
            e.Graphics.DrawString(s.Value, fn, new SolidBrush(Color.Black), r.Left + imageSize.Width, r.Top);
            e.DrawFocusRectangle();
        }
    }

     配合图文,给comboBox和ImageList添加内容

    void FillCbo(ComboBox cbo, ImageList img, IEnumerable<string> strLst)
    {
        img.Images.Clear();
        cbo.Items.Clear();
    
        Action<string> addItem = shortName =>
        {
            var bmp = GetPicFromName(shortName);
            img.Images.Add(bmp);
            cbo.Items.Add(new KeyValuePair<string, string>(shortName, string.Format("{0}({1})", DisplayText, shortName)));
        };
        foreach (var item in strLst)
            addItem(item);
    }

    另外,还需要修改comboBox的属性:

    cbo.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
    cbo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

    还有一个问题值得留意。本来在程序的处理代码里面我将Drawmode设置成OwnerDrawFixed,但是由于列项很多,有100多项,设置成这个选项之后,MaxDropDownItems=8失效了,后来改成OwnDrawVariable就可以了。两者相较,后者的灵活空间应该更大,可以手动调整的范围更广,对技术的要求也更高。

  • 相关阅读:
    MySql基础教程(三)——查询训练
    MySql基础教程(二)
    MySql基础教程(一)
    解决Eclipse闪退问题的方法总结
    MySQL图形工具 MySQL GUI Tools的安装使用方法
    MySql5.6版修改用户登录密码
    Windows下MySQL解压版的配置
    js 数组容易弄混的那些方法
    如何使CSS--better(系列二)
    如何使CSS--better(系列一)
  • 原文地址:https://www.cnblogs.com/icyJ/p/cboWithImage.html
Copyright © 2011-2022 走看看