OwnerDrawVariable Combobox DropDown空白

时间:2013-02-26 03:37:17

标签: c# winforms combobox custom-controls

我开发了以下自定义组合框来增加项目的高度。完成后,当有滚动条时,下拉菜单的末尾会出现一个空白区域。 enter image description here 我该如何纠正这个问题?

class MyComboBoxXX : ComboBox
{
    public MyComboBoxXX():base()
    {
        this.DrawMode = DrawMode.OwnerDrawVariable;
        this.DropDownStyle = ComboBoxStyle.DropDownList;
        this.MaxDropDownItems = 5;
        this.IntegralHeight = false;         
    }

    protected override void OnMeasureItem(MeasureItemEventArgs e)
    {
        e.ItemHeight = 40;
        this.DropDownHeight = 40 * 5;        
    }
    protected override void OnDrawItem(DrawItemEventArgs e)
    {        
        e.DrawBackground();        
        var index = e.Index;    
        if (index < 0 || index >= Items.Count) return;    
        using (var brush = new SolidBrush(e.ForeColor))
        {            
            Rectangle rec = new Rectangle(e.Bounds.Left, e.Bounds.Top + ((e.Bounds.Height - ItemHeight) / 2), e.Bounds.Width, ItemHeight);
            e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, new SolidBrush(this.ForeColor), rec);
        }
        e.DrawFocusRectangle();
    }    
}

3 个答案:

答案 0 :(得分:1)

如果你仔细观察,看起来DropDown区域的顶部和底部都有一个1像素的边框。您可以通过向DropDownHeight添加2个像素来消除空间。

protected override void OnMeasureItem(MeasureItemEventArgs e)
{
    e.ItemHeight = 40;
    this.DropDownHeight = (40 * 5) + 2; //add 2 pixels to include the border
}



结果:
Combobox without the space at the end

答案 1 :(得分:0)

我认为如果DropDownHeight值小于OnMeasureItem方法覆盖中的最大数量,则应将其减少到适当数量的项目。

答案 2 :(得分:0)

需要存储默认的ItemHeight,因为从Normal更改DrawMode会导致2个像素的填充添加到项目高度。在调用ItemHeight之前需要检索Handle,因为它创建了句柄。如果没有这个,ItemHeight属性的值不正确。 http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/ComboBox.cs