WinForms组合框高度与ItemHeight不同

WinForms组合框高度与ItemHeight不同

问题描述:

我在Text和DropDown模式下使用组合框(默认),我想要X(例如40)的ItemHeight,但将组合框的Height设置为Y(例如20)。WinForms组合框高度与ItemHeight不同

原因是我打算将ComboBox用于快速搜索功能,其中用户键入文本和详细结果显示在列表项中。只需要一行输入。

不幸的是,Winforms自动将组合框的Height锁定到ItemHeight,我看不到改变这种情况的方法。

如何使组合框的HeightItemHeight不同?

+2

请分享控件的设计代码和什么需要 – Sajal

+0

我主要是开发Windows Phone和那里,如果我需要实现这样我用了一个快速搜索功能的UI图像用户键入的TextBox,以及在其下呈现搜索结果的列表视图。它工作得非常好,并为定制提供了很多空间。 – WPMed

+0

您是否尝试过更改DrawMode? – Pikoh

您需要做的是,首先将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(); 
    }