C# - 如何获得ComboBox的实际高度

时间:2013-09-18 06:45:54

标签: c# winforms combobox size

我知道ComboBox.Height无法轻易设置。可以使用Font进行更改。但我需要知道它的最终高度。它在窗口和控件显示之前不会更新。

我如何计算呢?当我运行此按钮时,按钮不在组合框的下方:

// my forms must be disigned by code only (no designer is used)
public class Form1: Form
{
    public Form1()
    {
        ComboBox box = new ComboBox();
        box.Font = new Font("Comic Sans MS", 100, FontStyle.Regular);
        Controls.Add(box);

        Button button = new Button();
        button.Text = "hello world";
        button.SetBounds(box.Left, box.Bottom, 256, 32);
        button.SetBounds(box.Left, box.Height, 256, 32); // doesn't work either
        Controls.Add(button);
    }
}

1 个答案:

答案 0 :(得分:1)

问题是,在ComboBox.Bottom被绘制之前,ComboBox属性不会更新以补偿字体大小。

解决方案是在Form.Load事件而不是构造函数中动态添加控件:

private void MainForm_Load(object sender, EventArgs e)
{
    ComboBox box = new ComboBox();
    box.Font = new Font("Comic Sans MS", 100, FontStyle.Regular);
    Controls.Add(box);

    Button button = new Button();
    button.Text = "hello world";
    button.SetBounds(box.Left, box.Bottom, 256, 32); 
    Controls.Add(button);
}
相关问题