Dynamically Creating Tabs in WPF

I've been experimenting with dynamically created tabs 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 once you figure out how to do it.  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.

/// <summary> /// Create a new tab, populate it with the passed in user control, /// and display it to the user. /// </summary> /// <param name="detail">UserControl to populate the tab with</param> /// <param name="name">Name of the tab</param> public void AddDetail(UserControl detail, string name) { // make sure the passed in arguments are good Debug.Assert(detail != null, "UserControl detail is null"); Debug.Assert(name != null, "string name is null"); // locate the TabControl that the tab will be added to TabControl itemsTab = (TabControl) this.FindName("ItemsTab"); Debug.Assert(itemsTab != null, "can't find ItemsTab"); // create and populate the new tab and add it to the tab control TabItem newTab = new TabItem(); newTab.Content = detail; newTab.Header = name; itemsTab.Items.Add(newTab); // display the new tab to the user; if this line is missing // you get a blank tab itemsTab.SelectedItem = newTab; }
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted @ Saturday, October 27, 2007 6:56 AM

Comments on this entry:

Gravatar # re: Dynamically Creating Tabs in WPF
by Donovan Crone at 3/9/2010 6:53 PM

Very nice! helped alot!
Gravatar # re: Dynamically Creating Tabs in WPF
by Hicham at 6/7/2010 7:30 PM

Hello,
I'm sorry to disturb you, but i'm just a biginner in WPF world, i did use you code as it is but my user control isn't displayed.
Thank you
Gravatar # re: Dynamically Creating Tabs in WPF
by Lakshman Tavag at 6/21/2010 5:32 PM

Is there anyway to create different template grids for the new tabs?
Say I want different tabs to display completely different types of information. How do I specify the format of my dynamically displayed tabs?
Thanks in advance for any help!
Gravatar # re: Dynamically Creating Tabs in WPF
by Nilesh at 10/7/2010 4:46 AM

Very Useful..
Thanks
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: