c# - 在 ComboBox 中绘制图像和文本

标签 c# winforms combobox

我在 WindowsForms 中有一个组合框,我手动绘制项目。每个项目都由图片和文本(Cell.Image 和 Cell.Title)组成,因此项目高度为 34 px。

我的问题是,当我下拉 ComboBox 时,只有 1 个项目可见。 MaxDropDownItems = 4 因此 ComboBox 将绘制 4 个项目。我知道我已经设置了 DropDownHeight = 34,但我想在 ComboBox 中没有项目时显示空矩形,如下图所示。

没有项目的组合框 - 好的: ComboBox with no item - OK

只有 1 个可见项目的组合框 - 不好: ComboBox with only 1 visible item - Bad

我的类派生自 ComboBox:

public class ComboBoxCells : ComboBox
{
    private List<Cell> _cells;

    public List<Cell> Cells
    {
        get { return this._cells; }
        set
        {
            this._cells = value;
            this.BeginUpdate();
            this.Items.Clear();

            if (value != null)
                this.Items.AddRange(value.ToArray());

            this.EndUpdate();
        }
    }

    public ComboBoxCells()
    {
        this.DrawMode = DrawMode.OwnerDrawVariable;
        this.DropDownHeight = 34;
        this.DropDownWidth = 200;
        this.DropDownStyle = ComboBoxStyle.DropDownList;
        this.MaxDropDownItems = 4;

        this.DrawItem += new DrawItemEventHandler(ComboBoxCells_DrawItem);
        this.MeasureItem += new MeasureItemEventHandler(ComboBoxCells_MeasureItem);
    }

    private void ComboBoxCells_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground();

        // Draw item inside comboBox
        if ((e.State & DrawItemState.ComboBoxEdit) != DrawItemState.ComboBoxEdit && e.Index > -1)
        {
            Cell item = this.Items[e.Index] as Cell;

            e.Graphics.FillRectangle(Brushes.Gray, new Rectangle(e.Bounds.Left + 6, e.Bounds.Top + 6, 22, 22));

            e.Graphics.DrawImage(item.Image, new Rectangle(e.Bounds.Left + 7, e.Bounds.Top + 7, 20, 20));

            e.Graphics.DrawString(item.Title, e.Font,
                    new SolidBrush(e.ForeColor), e.Bounds.Left + 34, e.Bounds.Top + 10);
        }
        // Draw visible text
        else if (e.Index > -1)
        {
            Cell item = this.Items[e.Index] as Cell;

            e.Graphics.DrawString(item.Title, e.Font,
                    new SolidBrush(e.ForeColor), e.Bounds.Left, e.Bounds.Top);
        }

        e.DrawFocusRectangle();
    }

    private void ComboBoxCells_MeasureItem(object sender, MeasureItemEventArgs e)
    {
        e.ItemHeight = 34;
    }
}

谢谢

最佳答案

DropDownHeight 是您想要设置更高的数字。它是下拉框的最大像素数。系统会自动将其设为您的元素高度的最大倍数。

this.DropDownHeight = 200;

关于c# - 在 ComboBox 中绘制图像和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5677117/

相关文章:

c# - 如何在 Azure 中检索保存的对话数据(Tablelogger)

c# - 在 EF Core 中添加迁移时出现 "The entity type ' CustomAttributeData ' requires a primary key to be defined"错误

c# - 如何在 GridView 中编辑 Linkcolumn 类型的单元格

c# - WinForm刷新问题

WPF - 将 ValidationRules 绑定(bind)到 Combobox.Text 属性

c# - 在 winforms ComboBox 中为单个项目上色?

c# - 使用Ping映射事件IP的线程问题-C#

c# - LINQ on HashSet 与 List 的对比

c# - 如何在图表控件中添加网格右边框

python - 为什么 tkinter.ttk Combobox 仅在初始选择时清除显示值?