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

  • 相关阅读:
    1.线程是什么?
    eclipse新手知识点1
    《图解Java多线程设计模式》UML用什么软件画?
    Microsoft SQL Server 2008完整+差异备份及还原实战
    xcopy
    导入EXCEL到数据库表中的步骤:
    js判断一个值是空的最快方法是不是if(!value){alert("这个变量的值是null");}
    Pytorch1.6.0 Nvidia Jetson TX2
    python所有的print就会自动打印到log.txt
    python import numpy right but import caffe wrong
  • 原文地址:https://www.cnblogs.com/icyJ/p/cboWithImage.html
Copyright © 2011-2022 走看看