Как установить высоту ComboBox? - PullRequest
22 голосов
/ 01 июля 2010

У меня есть ComboBox на форме, и его высота по умолчанию равна 21. Как я могу изменить его?

Ответы [ 7 ]

25 голосов
/ 01 июля 2010

ComboBox авто-размеры, чтобы соответствовать шрифту.Отключить это не вариант.Если вы хотите, чтобы это было больше, тогда дайте ему больший шрифт.

13 голосов
/ 01 июля 2010

Установите DrawMode на OwnerDrawVariable.Однако настройка ComboBox приводит к другим проблемам.Смотрите эту ссылку для учебника о том, как сделать это полностью:

http://www.csharphelp.com/2006/09/listbox-control-in-c/

OwnerDrawVariable пример кода здесь: https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.drawitem%28v=vs.110%29.aspx

Как только это будет сделаноВам необходимо установить свойство ItemHeight в выпадающем списке, чтобы задать эффективную высоту выпадающего списка.

6 голосов
/ 23 августа 2015

Точно так же, если вы хотите увеличить высоту ComboBox, не увеличивая размер шрифта или не заботясь о том, чтобы рисовать все самостоятельно, вы можете использовать простой вызов Win32 API для увеличения высоты, как это:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Win32ComboBoxHeightExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
        private const Int32 CB_SETITEMHEIGHT = 0x153;

        private void SetComboBoxHeight(IntPtr comboBoxHandle, Int32 comboBoxDesiredHeight)
        {
            SendMessage(comboBoxHandle, CB_SETITEMHEIGHT, -1, comboBoxDesiredHeight);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SetComboBoxHeight(comboBox1.Handle, 150);
            comboBox1.Refresh();
        }
    }
}

Результат:

enter image description here

1 голос
/ 18 октября 2018

Для этого вам нужно установить DrawMode на OwnerDrawVariable или OwnerDrawFixed и вручную нарисовать ваши предметы.Это можно сделать с помощью довольно простого класса.

Этот пример позволит вам использовать свойство ItemHeight ComboBox независимо от размера шрифта.Я добавил бонусное свойство TextAlign, которое также позволит вам центрировать элементы.

Стоит отметить, что вы должны установить DropDownStyle в DropDownList, чтобы выбранный элемент соответствовал нашим настройкам.

// The standard combo box height is determined by the font. This means, if you want a large text box, you must use a large font.
// In our class, ItemHeight will now determine the height of the combobox with no respect to the combobox font.
// TextAlign can be used to align the text in the ComboBox
class UKComboBox : ComboBox
{

    private StringAlignment _textAlign = StringAlignment.Center;
    [Description("String Alignment")]
    [Category("CustomFonts")]
    [DefaultValue(typeof(StringAlignment))]
    public StringAlignment TextAlign
    {
        get { return _textAlign; }
        set
        {
            _textAlign = value;
        }
    }

    private int _textYOffset = 0;
    [Description("When using a non-centered TextAlign, you may want to use TextYOffset to manually center the Item text.")]
    [Category("CustomFonts")]
    [DefaultValue(typeof(int))]
    public int TextYOffset
    {
        get { return _textYOffset; }
        set
        {
            _textYOffset = value;
        }
    }


    public UKComboBox()
    {
            // Set OwnerDrawVariable to indicate we will manually draw all elements.
            this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
            // DropDownList style required for selected item to respect our DrawItem customizations.
            this.DropDownStyle = ComboBoxStyle.DropDownList;
            // Hook into our DrawItem & MeasureItem events
            this.DrawItem +=
                new DrawItemEventHandler(ComboBox_DrawItem);
            this.MeasureItem +=
                new MeasureItemEventHandler(ComboBox_MeasureItem);

    }

    // Allow Combo Box to center aligned and manually draw our items
    private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
    {


        // Draw the background
        e.DrawBackground();

        // Draw the items
        if (e.Index >= 0)
        {
            // Set the string format to our desired format (Center, Near, Far)
            StringFormat sf = new StringFormat();
            sf.LineAlignment = _textAlign;
            sf.Alignment = _textAlign;

            // Set the brush the same as our ForeColour
            Brush brush = new SolidBrush(this.ForeColor);

            // If this item is selected, draw the highlight
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                brush = SystemBrushes.HighlightText;

            // Draw our string including our offset.
            e.Graphics.DrawString(this.Items[e.Index].ToString(), this.Font, brush, 
                new RectangleF(e.Bounds.X, e.Bounds.Y + _textYOffset, e.Bounds.Width, e.Bounds.Height), sf);
        }

    }


    // If you set the Draw property to DrawMode.OwnerDrawVariable, 
    // you must handle the MeasureItem event. This event handler 
    // will set the height and width of each item before it is drawn. 
    private void ComboBox_MeasureItem(object sender,System.Windows.Forms.MeasureItemEventArgs e)
    {
        // Custom heights per item index can be done here.
    }

}

Теперь у нас есть полный контроль над нашим шрифтом и высотой ComboBox отдельно.Нам больше не нужно делать крупный шрифт для размера нашего ComboBox.

enter image description here

0 голосов
/ 22 июня 2019

ComboBox имеет свойство DropDownHeight, которое может быть изменено либо через окно свойств комбинированного списка, либо программно. т.е.

public partial class EventTestForm : Form
{
    public EventTestForm()
    {
        InitializeComponent();
        cmbOwners.DropDownHeight = 100;
    }
0 голосов
/ 11 января 2018

Если вы хотите настроить количество элементов в ComboBox, вы можете изменить значение DropDownHeight следующим образом, учитывая Список элементов.Я использую 24 здесь как «на единицу товара»;это ни в коем случае не исправлено.

  comboBox1.DropDownHeight = SomeList.Count * 24;
0 голосов
/ 01 июля 2010

В коде a.Hight должен работать. В конструкторе зайдите в свойства и посмотрите в Размер-> Высота.

Кроме того, вы можете изменить размер шрифта, и поле со списком увеличится, чтобы вместить его, но я не думаю, что это то, что вы хотите.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...