【问题标题】:Change Item Height of ComboBox更改组合框的项目高度
【发布时间】:2016-02-11 06:44:12
【问题描述】:

如何设置组合框项的高度?我的 combobox.size=new size(320,40) 和我设置了 combobox.itemheight=18 但它没有用。我希望我的 itemheight 或文本高度为 18,并且组合框的固定大小为 320x40。我也使用了 drawmode 属性,但什么也没发生。

【问题讨论】:

  • DrawMode改为OwnerDrawFixed,然后将ItemHeight设置为你想要的值;但是,您必须手动绘制项目。

标签: c# winforms


【解决方案1】:

尝试更改组合框的字体大小

【讨论】:

  • 我试过 ComboBox.ItemHeight = 18 但也没有用
  • 更改其字体大小而不是 itemheight
  • ComboBox.Font = new Font("Tahoma",18, FontStyle.Bold);它改变了字体高度,但组合框高度也在改变,变得更短
【解决方案2】:

好吧,为了防止组合框调整到默认高度,你可以声明它是手动绘制的:

myComboBox.DrawMode = DrawMode.OwnerDrawFixed; // or DrawMode.OwnerDrawVariable;
myComboBox.Height = 18; // <- what ever you want

那你要实现DrawItem事件:

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

编辑:使组合框拉伸,但它的下拉列表

   myComboBox.DrawMode = DrawMode.OwnerDrawVariable; 
   myComboBox.Height = 18; // Combobox itself is 18 pixels in height

   ...

   private void myComboBox_MeasureItem(object sender, MeasureItemEventArgs e) {
     e.ItemHeight = 17; // while item is 17 pixels high only
   }

【讨论】:

  • @XXX: 因为它是OwnerDraw,所以你的任务是获得合适的字体(或至少大小);你坚持的高度超过了推荐的高度,所以立竿见影的效果是间距很大;另一种可能性是OwnerDrawVariable 模式和MeasureItem 事件;查看我的编辑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-06
相关资源
最近更新 更多