Placing Images and Strings with a C# Combobox

前端 未结 5 1618
傲寒
傲寒 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:24

    Very helpful.. some optimisations :

    public sealed class ColorSelector : ComboBox
    {
        public ColorSelector()
        {
            DrawMode = DrawMode.OwnerDrawFixed;
            DropDownStyle = ComboBoxStyle.DropDownList;
        }
    
        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            e.DrawBackground();
    
            e.DrawFocusRectangle();
    
            if (e.Index >= 0 && e.Index < Items.Count)
            {
                DropDownItem item = (DropDownItem)Items[e.Index];
    
                e.Graphics.DrawImage(item.Image, e.Bounds.Left, e.Bounds.Top);
    
                e.Graphics.DrawString(item.Value, e.Font, new SolidBrush(e.ForeColor), e.Bounds.Left + item.Image.Width, e.Bounds.Top + 2);
            }
    
            base.OnDrawItem(e);
        }
    }
    

    and ...

    public sealed class DropDownItem
    {
        public string Value { get; set; }
    
        public Image Image { get; set; }
    
        public DropDownItem()
            : this("")
        { }
    
        public DropDownItem(string val)
        {
            Value = val;
            Image = new Bitmap(16, 16);
            using (Graphics g = Graphics.FromImage(Image))
            {
                using (Brush b = new SolidBrush(Color.FromName(val)))
                {
                    g.DrawRectangle(Pens.White, 0, 0, Image.Width, Image.Height);
                    g.FillRectangle(b, 1, 1, Image.Width - 1, Image.Height - 1);
                }
            }
        }
    
        public override string ToString()
        {
            return Value;
        }
    }
    

提交回复
热议问题