Adding a Close Context Menu to TabItem in WPF

Continuing the previous post

let us add the Close Context menu to our TabItem.

To do this we need to add the Context Menu tag to the DataTemplate defined for the Tab.

<TabControl Height="271" HorizontalAlignment="Left" Margin="123,9,0,0" Name="mainTabControl" VerticalAlignment="Top" Width="441"
 IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding ObservableCollectionTabItems}" Background="White">
 <TextBlock Text="{Binding Header}" >
 <MenuItem Header="Close" Click="MenuItem_Click">

Add the following code to the ViewModel class for the MainWindow.

public void CloseTabItem(Object sender)
 VMParentForViews vmParentForViews = (sender as MenuItem).DataContext as VMParentForViews;

Call the above method from the code behind of the MainWindow’s MenuItem_Click event

This is how the Close menu looks like, clicking on it closes the tab item. (i.e. removes it from the ObservableCollection to which tab control is bind)

The sample application link!338&parid=root

Hope it helps


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

One thought on “Adding a Close Context Menu to TabItem in WPF”

Please share your thoughts

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

You are commenting using your 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.