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

  • 相关阅读:
    async简单使用
    node调用phantomjs-node爬取复杂页面
    mongodb3 ubuntu离线安装(非apt-get)及用户管理
    2040-亲和数(java)
    JavaScript闭包简单理解
    nodejs构建多房间简易聊天室
    linux下安装nodejs及npm
    EventBus轻松使用
    mysql用户创建及授权
    python中json的基本使用
  • 原文地址:https://www.cnblogs.com/icyJ/p/cboWithImage.html
Copyright © 2011-2022 走看看