如何使ToolStripComboBox填充ToolStrip上的所有可用空间?

时间:2010-05-04 21:26:40

标签: c# winforms toolstrip toolstripcombobox

ToolStripComboBox放在ToolStripButton之后,后面是另一个右对齐的。如何最好地设置ToolStripComboBox以始终调整其长度以填充前面和下面的ToolStripButtons之间的所有可用空间?

过去我曾经处理父调整大小事件,根据相邻元素坐标计算要设置的新长度并设置新大小。但是现在,当我开发一个新的应用程序时,我想知道是否没有更好的方法。

3 个答案:

答案 0 :(得分:5)

我使用以下内容取得了巨大成功:

private void toolStrip1_Layout(System.Object sender, System.Windows.Forms.LayoutEventArgs e)
{
    int width = toolStrip1.DisplayRectangle.Width;

    foreach (ToolStripItem tsi in toolStrip1.Items) {
        if (!(tsi == toolStripComboBox1)) {
            width -= tsi.Width;
            width -= tsi.Margin.Horizontal;
        }
    }

    toolStripComboBox1.Width = Math.Max(0, width - toolStripComboBox1.Margin.Horizontal);
}

上述代码不会受到控制问题的影响。

答案 1 :(得分:2)

此处没有自动布局选项。但您可以通过实现ToolStrip.Resize事件轻松完成。这很有效:

    private void toolStrip1_Resize(object sender, EventArgs e) {
        toolStripComboBox1.Width = toolStripComboBox2.Bounds.Left - toolStripButton1.Bounds.Right - 4;
    }
    protected override void OnLoad(EventArgs e) {
        toolStrip1_Resize(this, e);
    }

请务必将TSCB的AutoResize属性设置为False,否则它将无效。

答案 2 :(得分:1)

ToolStrip ts = new ToolStrip();

ToolStripComboBox comboBox = new TooLStripComboBox();
comboBox.Dock = DockStyle.Fill;

ts.LayoutStyle = ToolStripLayoutStyle.Table;
((TableLayoutSettings)ts.LayoutSettings).ColumnCount = 1;
((TableLayoutSettings)ts.LayoutSettings).RowCount = 1;
((TableLayoutSettings)ts.LayoutSettings).SetColumnSpan(comboBox,1);

ts.Items.Add(comboBox);

现在组合框将正确对接填充。相应地设置列或行范围。