简体   繁体   中英

Group related controls on ToolStrip so they are always visible together

I have an application that has a tool strip with related controls set apart by ToolStripSeparaters. It looks something like this:

场景宽度足够的屏幕宽度。相关控件一起显示。

However, when the window size shrinks, some of the controls get moved to a little drop-down section. Unfortunately, this can split related controls, for example in the screenshot below, the "Filter by ID" label, the associated textbox for the ID, and "Clear Filter" button are no longer shown together.

较窄的窗口与相关控件分开

If controls have to be moved to the drop-down, I'd prefer to have related controls move together. Is there a way to group related controls together on a ToolStrip? Or perhaps a better way of dealing with this sort of scenario?


I tried using the LayoutCompleted event move all of the controls to the overflow area if any of them are in the overflow.

private void toolStrip1_LayoutCompleted(object sender, EventArgs e)
{
  var filterGroup = new List<ToolStripItem> { lblFilter, txtFilter, btnClearFilter };
  if (filterGroup.Any(x => x.IsOnOverflow))
  {
    filterGroup.ForEach(x => x.Overflow = ToolStripItemOverflow.Always);
  }
}

This seems to work fine, but I haven't found a good way to show them again when the window size is increased. I tried both the Resize and Layout events of the ToolStrip with the following code:

var filterGroup = new List<ToolStripItem> { lblFilter, txtFilter, btnClearFilter };
filterGroup.ForEach(x => x.Overflow = ToolStripItemOverflow.AsNeeded);

You could use a ToolStripControlHost to group a winforms TextBox and Label . Eg

public class ToolStripLabelTextBox : ToolStripControlHost {

    public Label Label { get; private set; }
    public TextBox TextBox { get; private set; }

    public ToolStripLabelTextBox(String labelText) : base(new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, WrapContents = false, AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, Padding = Padding.Empty, Margin = Padding.Empty }) {
        Label = new Label { Text = labelText, AutoSize = true, Anchor = AnchorStyles.Top | AnchorStyles.Bottom, TextAlign = System.Drawing.ContentAlignment.MiddleCenter };
        TextBox = new TextBox();

        FlowLayoutPanel panel = (FlowLayoutPanel) Control;
        panel.Controls.Add(Label);
        panel.Controls.Add(TextBox);
    }
}

Two other options are:

  1. Implement a LayoutEngine that does the grouping you want.
  2. Implement a composite ToolStripItem that displays a label and text box. You can use the ToolStripRadioButtonMenuItem as an example: https://msdn.microsoft.com/en-us/library/vstudio/ms404318%28v=vs.100%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM