Dynamically Creating Tabs in WPF

Posted: April 22, 2013 by Sagar Wasule in Asp.Net, Programming Concepts, WPF
Tags: ,

In one of my recent project which I undertook I had to create tabs dynamically in WPF.  The idea is that the user selects a menu item and a tab is created and populated with a user control.  Like so many things, WPF makes this easy.  The thing I struggled with the most was getting the user control to display when the first tab was created.  Below is a function that takes a user control and tab name, creates a tab, and shows it to the user.


Code for the above scenario is below :

/// Create a new tab, populate it with the passed in user control,
/// and display it to the user.
/// UserControl to populate the tab with
/// Name of the tab
public void AddDetail(UserControl detail, string name)
{
// locate the TabControl that the tab will be added to
TabControl itemsTab = (TabControl) this.FindName("ItemsTab");

// create and populate the new tab and add it to the tab control
TabItem Tab1 = new TabItem();
Tab1.Content = detail;
Tab1.Header = name;
itemsTab.Items.Add(Tab1);

// display the new tab to the user; if this line is missing
// you get a blank tab
itemsTab.SelectedItem = Tab1;
}

This explains adding a new tab in tabcontrol but if you want to delete any particular tab from tabcontrol the code that can be used for the same will be :



itemsTab.Items.Remove(Tab1);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s