【问题标题】:Winforms ComboBox Height different to ItemHeightWinforms ComboBox Height 与 ItemHeight 不同
【发布时间】:2016-05-17 06:35:01
【问题描述】:

我在 Text 和 DropDown 模式(默认)下使用 ComboBox,我希望将 ItemHeight 设为 X(例如 40),但将 ComboBox 的 Height 设置为 Y(例如 20)。

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

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

如何使 ComboBox 的 HeightItemHeight 不同?

【问题讨论】:

  • 请分享控件的设计器代码和所需的 UI 图像
  • 我主要在 Windows Phone 中开发,如果我需要实现这样的快速搜索功能,我会使用一个 TextBox 供用户输入,并在其下使用一个列表视图来呈现搜索结果。效果很好,并提供了很大的定制空间。
  • 你试过改变DrawMode吗?

标签: c# winforms combobox


【解决方案1】:

你要做的是,首先将DrawModeNormal改为OwnerDrawVariable。然后你必须处理 2 个事件: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();
    }

【讨论】:

    猜你喜欢
    • 2012-10-08
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2011-04-21
    • 2010-11-04
    • 2012-01-18
    • 1970-01-01
    相关资源
    最近更新 更多