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

Top
推荐
收藏
关注
评论
posted @ 2014-05-14 10:53  脸谱匠  阅读(2228)  评论(0编辑  收藏  举报