2016-05-17 66 views
0

我在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

回答

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(); 
    }