Add tabs to a WPF TabControl at runtime in C#

[WPF TabControl]

When you click the + button, this example uses the following code to add a tab to the WPF TabControl named tabMain.

// Add a tab to the TabControl.
private void btnAdd_Click(object sender, RoutedEventArgs e)
    TabItem tab_item = new TabItem();

    Label label = new Label();
    label.Content = "New Tab";
    tab_item.Header = label;

    Label content = new Label();
    content.Content = "This is the new tab's content";
    tab_item.Content = content;

First the code creates a TabItem and adds it to the WPF TabControl object’s Items collection.

It then creates a Label and places it in the new TabItem object’s Header property. Whatever you place in the Header is what appears at the top of the tab. This example uses a Label but you can place any single control here. For example, you could use a Grid and then place other controls inside the Grid.

Next the code makes a second Label and places it in the TabItem object’s Content property. Again this must be a single control, although you can make it a container such as a Grid and then place as many controls as you like inside the Grid.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in controls and tagged , , , , , , , , , , , , , . Bookmark the permalink.

1 Response to Add tabs to a WPF TabControl at runtime in C#

Comments are closed.