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就可以了。两者相较,后者的灵活空间应该更大,可以手动调整的范围更广,对技术的要求也更高。

  • 相关阅读:
    catchadminvue 安装遇到的问题
    HttpRunner 3.x (三)环境与简介 测试
    HttpRunner 3.x (五):variables变量的声明和引用 测试
    HttpRunner 3.x (四):post请求类型application/xwwwfromurlencoded 测试
    httprunenr 3.x(一)环境安装与准备 测试
    httprunner 3.x(二)测试用例结构 测试
    单例模式,工厂模式
    【更新公告】Airtest更新至1.2.4
    【更新公告】pocoui更新至1.0.85版本
    使用Airtest对iOS进行自动化的常见问题答疑
  • 原文地址:https://www.cnblogs.com/icyJ/p/cboWithImage.html
Copyright © 2011-2022 走看看