1

I have an app with a Tab interface.
Each Tab could essentially be an app in itself.

The main menu contains options that apply to the content of Tab 1.
Tabs 2 and three need a completely different menu.

How can I swap menus as the user clicks on a different Tab? Do I need to rebuild the main menu every time or is there a way to have a menu bar that is associated with a tab?

Jimi
  • 29,621
  • 8
  • 43
  • 61
user471230
  • 81
  • 7
  • You can do that as shown here: [Can I show the ToolStrip of a child Form in the MDIParent Form?](https://stackoverflow.com/a/61563839/7444103) (never mind the question is related to MDI child Forms, the ToolStripManager works the same no matter what the source of the MenuStrip). You can add the MenuStrip to a TabPage, but that's not what I'd suggest. You can instead use a `Dictionary` and select a MenuStrip to merge based on the index of current TabPage selected. If you cannot get it to work, let me know. – Jimi Jun 30 '20 at 01:27

1 Answers1

0

MenuStrips and TabPages are Controls. You can add Controls to other Controls as Child controls using Control.Controls.Add(...). Use MenuStrip.Dock to Dock it on the desired position. Maybe you need to set the Size of the MenuStrip.

Although this will work, I'm not sure if this is wise. People don't expect menus to be scattered all around your window. Wouldn't it be better to change the Main menu when you select a different TabPage?

Let every TabPage have its own MenuStrip, and when a new TabPage is selected, let your form change the menu.

class MyTabPage : TabPage
{
    ...
    public MenuStrip MenuStrip => ...
}

If you don't want to create a special TabPage class, consider using property Tag to store the MenuStrip.

In your form:

// probably done in InitializeComponent()
private TabControl tabControl = ...

// access to the TabPages and to the Selected tab:
private IEnumerabl<MyTabPage> TabPages => this.TabControl.TabPages.Cast<MyTabPage>();
private MyTabPage SelectedTabPage => (MyTabPage)this.TabControl.SelectedPage;

// constructor
public MyForm()
{
    InitializeComponent();
    AddTabPages();  // only if needed

    // add the menu strips of all tab pages to this.Controls
    IEnumerable<MenuStrip> menuStrips = this.TabPages
        .Select(tabPage => tabPage.MenuStrip);
    this.Controls.AddRange(menuStrips)

    // get notified when selected tab page changes:
    this.TabControl.SelectedIndexChanged
    tabControl.SelectedIndexChanged += OnTabPageChanged;
}

private MyTabPage SelectedTabPage => (MyTabPage)tabControl.SelectedTab();

private void OnTabPageChanged(object sender, ...)
{
    // change the main menu:
    this.MainMenuStrip = this.SelectedTabPage?.MenuStrip;
}
Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116