Placing Images and Strings with a C# Combobox

前端 未结 5 1586
傲寒
傲寒 2020-12-01 14:30

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 o

5条回答
  •  無奈伤痛
    2020-12-01 15:10

    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.

    Image:

    Drop Down Color Selector


    Code:

    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;
        }
    }
    

提交回复
热议问题