使用C#组合框放置图像和字符串 [英] Placing Images and Strings with a C# Combobox

查看:152
本文介绍了使用C#组合框放置图像和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为Windows窗体应用程序创建一个下拉菜单或组合框,其中包含一个小图片,然后是一个旁边的文本字符串。基本上,您可以在下拉列表中想到每个行,因为需要有一个图标,然后是图标右侧的图标名称。我有麻烦这样做 - 事实上,我完全不成功。有没有人知道一个方法来完成这个任务?任何帮助将非常感激。谢谢!

I need to create a dropdown menu, or combobox, for a Windows Forms application which contains a small image and then a string of text next to it. Basically, you can think of each 'row' in the dropdown as needing to have an icon and then the name of the icon to the right of the icon. I am having trouble doing this -- in fact, I've been completely unsuccessful. Does anyone know of a way to accomplish this task? Any help will be greatly appreciated. Thanks!

推荐答案

我能够提出一些非常简单的代码来执行这个(见下面的代码片段)。代码创建一个控件,它是一个下拉控件,显示一个小的彩色正方形和同一行中的颜色的名称(见照片)。感谢您提供的链接,当它最初发布!希望此控制项可以在将来帮助别人。

I was able to come up with some very simple code to perform this (see snippet below). The code creates a control that is a dropdown control which shows a small colored square and that color's name in the same row (see photo). Thanks for the links provided for this back when it was originally posted! Hopefully this control can help someone else out in the future.

图片:

代码:

class ColorSelector : ComboBox
{
    public ColorSelector()
    {
        DrawMode = DrawMode.OwnerDrawFixed;
        DropDownStyle = ComboBoxStyle.DropDownList;
    }

    // Draws the items into the ColorSelector object
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        e.DrawBackground();
        e.DrawFocusRectangle();

        DropDownItem item = DropDownItem(Items[e.Index].ToString());
        // Draw the colored 16 x 16 square
        e.Graphics.DrawImage(item.Image, e.Bounds.Left, e.Bounds.Top);
        // Draw the value (in this case, the color name)
        e.Graphics.DrawString(item.Value, e.Font, new
                SolidBrush(e.ForeColor), e.Bounds.Left + item.Image.Width, e.Bounds.Top + 2);

        base.OnDrawItem(e);
    }
}

public class DropDownItem
{
    public string Value
    {
        get { return value; }
        set { this.value = value; }
    }
    private string value;

    public Image Image
    {
        get { return img; }
        set { img = value; }
    }
    private Image img;

    public DropDownItem() : this("")
    {}

    public DropDownItem(string val)
    {
        value = val;
        this.img = new Bitmap(16, 16);
        Graphics g = Graphics.FromImage(img);
        Brush b = new SolidBrush(Color.FromName(val));
        g.DrawRectangle(Pens.White, 0, 0, img.Width, img.Height);
        g.FillRectangle(b, 1, 1, img.Width - 1, img.Height - 1);
    }

    public override string ToString()
    {
        return value;
    }
}

这篇关于使用C#组合框放置图像和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆