Adding TabItem at runtime in a C# WPF application

In this article we will be creating certain tabs in a tab control with context menu with an option to remove certain tab item.

First create a blank c# WPF application using visual studio 2008 and name the default grid as Master.

Right click on window and select view code,

Here we create a method to remove a tabItem. The method accepts a TabItem needed to be removed as parameter.

private void closeTabItem(TabItem item)
    {
 
        if (item != null)
        {
 
            // find the parent tab control
 
            TabControl tabControl = item.Parent as TabControl;
 
            if (tabControl != null)
 
                tabControl.Items.Remove(item); // remove tabItem
 
        }
 
    }

Now Double click the window and add this code to window load event.

       // Create Context Menu
 
        ContextMenu contextMenu1;
 
        contextMenu1 = new ContextMenu();
 
        //Create menu items
 
        MenuItem menuItem1;
 
        menuItem1 = new MenuItem();
 
        //add menu item in context menu
 
        contextMenu1.Items.Add(menuItem1);
 
        menuItem1.Header = "Close"; // define name of context menu
 
        //Create Tab Items
 
        TabItem Item1 = new TabItem();
 
        Item1.Header = "Tab1";
 
        TabItem Item2 = new TabItem();
 
        Item2.Header = "Tab2";
 
        // define clicking event of menuitem
 
        menuItem1.Click += delegate { closeTabItem(Item1); };
 
        // Incorporate context menu with tab items
 
        Item1.ContextMenu = contextMenu1;
 
        //Create tab Control
 
        TabControl tabControl1 = new TabControl();
 
        //Insert Tab Items in Tab Control
 
        tabControl1.Items.Add(Item1);
 
        tabControl1.Items.Add(Item2);
 
        Master.Childer.Add(tabControl1); // Insert Tab Control in Master Grid

Now Compile and execute the project. On right click on Tab1 you will see a pop-up menu with close option to close (remove) that tabItem.