Winforms ComboBox Height different to ItemHeight



我在文本和下拉模式(默认模式)下使用组合框,我希望ItemHeight为X(例如40),但将组合框的Height设置为Y(例如20)。

这样做的原因是,我打算将组合框用于快速搜索功能,在该功能中,用户键入文本并在列表项中呈现详细结果。只需要一行输入。

不幸的是,Winforms会自动将ComboBox的Height锁定到ItemHeight,我看不出有什么办法可以改变这一点。

如何使组合框的HeightItemHeight不同?

首先要做的是将DrawModeNormal更改为OwnerDrawVariable。然后您必须处理两个事件:DrawItemMeasureItem。它们可能类似于:

    private void comboBox1_MeasureItem(object sender, MeasureItemEventArgs e)
    {
        e.ItemHeight = 40; //Change this to your desired item height
    }

    private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        ComboBox box = sender as ComboBox;
        if (Object.ReferenceEquals(null, box))
            return;
        e.DrawBackground();
        if (e.Index >= 0)
        {
            Graphics g = e.Graphics;
            using (Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                                  ? new SolidBrush(SystemColors.Highlight)
                                  : new SolidBrush(e.BackColor))
            {
                using (Brush textBrush = new SolidBrush(e.ForeColor))
                {
                    g.FillRectangle(brush, e.Bounds);
                    g.DrawString(box.Items[e.Index].ToString(),
                                 e.Font,
                                 textBrush,
                                 e.Bounds,
                                 StringFormat.GenericDefault);
                }
            }
        }
        e.DrawFocusRectangle();
    }

最新更新