c# - 使用 C# 组合框放置图像和字符串

标签 c# winforms image combobox drop-down-menu

我需要为 Windows 窗体应用程序创建一个下拉菜单或组合框,其中包含一个小图像,然后是旁边的一串文本。基本上,您可以认为下拉列表中的每一行都需要一个图标,然后是图标右侧的图标名称。我在做这件事时遇到了麻烦——事实上,我完全没有成功。有谁知道完成这项任务的方法?任何帮助将不胜感激。谢谢!

最佳答案

我能够想出一些非常简单的代码来执行此操作(请参见下面的代码片段)。该代码创建一个控件,它是一个下拉控件,在同一行中显示一个小的彩色方 block 和该颜色的名称(见图)。感谢您在最初发布时为此提供的链接!希望此控件将来可以帮助其他人。

图片:

Drop Down Color Selector


代码:

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 = new 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# - 使用 C# 组合框放置图像和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1232861/

相关文章:

c# - Entity Framework Code First 现有数据库集 EntityState.Unchanged on Many-to-Many

c# - tabControl 中的关闭按钮

c# - 使用不可选择的项目创建 WinForms ComboBox

jQuery 用图像填充正文

c# - 如何让智能手机像滚动 winforms 触摸屏应用程序一样(滚动面板)

c# - 使用客户端证书的 WCF 传输安全

c# - WPF 中 DisplayFormatAttribute 的推荐替代方法是什么?

c# - 将 DataSource 属性添加到自定义 WinForms 控件

java - 将 double int[][] 图像减小到更小的尺寸

image - Canvas drawImage 在 CustomPainter 中缩放高度和宽度