在ComboBox中绘制图像和文本

| 我在WindowsForms中有一个ComboBox,并且我手动绘制项目。每个项目都由图片和文字(Cell.Image和Cell.Title)组成,因此项目的高度为34 px。 我的问题是,当我下拉ComboBox时,只有1个项目可见。 MaxDropDownItems = 4,因此ComboBox将绘制4个项目。我知道我已经设置了DropDownHeight = 34,但是我想在ComboBox中没有任何项目时显示空矩形,如下图所示。 没有项目的组合框-确定: 只有1个可见项目的ComboBox-错误: 我的课程来自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;
    
如果将
IntegralHeight
设置为true,它将调整下拉列表的大小,因此不会显示部分项目。它应该摆脱空白。     
在您的
ComboBoxCells() constructor
中,添加可以绘制高度为34像素的白色矩形的默认单元格项目。 在
List<Cell> Cells Set property
中,删除该项目并添加by5ѭ指定的新项目。这样可以确保在指定项目列表时都删除默认项目,否则请绘制默认项目。 在
ComboBoxCells_DrawItem() event
中,以
e.Index = 0
条件处理此更改并绘制矩形。 希望这种方法对您有用。     

要回复问题请先登录注册