IntroductionIn this article we will see how we can achieve the
Closable Tab Item in Tab Control in WPF.
Crating WPF Application
ProjectFire up Visual Studio 2008 and Create a WPF Application and
name the project as SampleTabControl.

First
we need to create a Resource Dictionary where we would make our custom
control.

Now
before designing the custom control write the below CS file which is the class
that would inherit TabItem.

Write
the following code into the cs file as follows:
public class CloseableTabItem : TabItem
{
static CloseableTabItem()
{
//This style is defined in themes\generic.xaml
DefaultStyleKeyProperty.OverrideMetadata(typeof(CloseableTabItem),
new FrameworkPropertyMetadata(typeof(CloseableTabItem)));
}
public static readonly RoutedEvent CloseTabEvent =
EventManager.RegisterRoutedEvent("CloseTab", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(CloseableTabItem));
public event RoutedEventHandler CloseTab
{
add { AddHandler(CloseTabEvent, value); }
remove { RemoveHandler(CloseTabEvent, value); }
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
Button closeButton = base.GetTemplateChild("PART_Close") as Button;
if (closeButton != null)
closeButton.Click += new System.Windows.RoutedEventHandler(closeButton_Click);
}
void closeButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
this.RaiseEvent(new RoutedEventArgs(CloseTabEvent, this));
}
}Our
resource dictionary need to changed based on our style. The following XAML
represents it.
Now we would design our application, the
basic need is to have one Add Button and A Tab Control. See below
figure.

The
following figure is for your XAML reference.
Now
in the Button Click event write the below code to add a TabItem at
runtime.
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
CloseableTabItem tabItem = new CloseableTabItem();
tabItem.Header = "New Tab";
MainTab.Items.Add(tabItem);
}For
closing the TabItem add the Handler for it. Follow below code:
public Window1()
{
InitializeComponent();
this.AddHandler(CloseableTabItem.CloseTabEvent, new RoutedEventHandler(this.CloseTab));
}
private void CloseTab(object source, RoutedEventArgs args)
{
TabItem tabItem = args.Source as TabItem;
if (tabItem != null)
{
TabControl tabControl = tabItem.Parent as TabControl;
if (tabControl != null)
tabControl.Items.Remove(tabItem);
}
}Now
our application is ready to test. Run it.

That's
it. We have successfully achieved adding and removing tabs at run
time.
Hope this article helps.