Adding a Close Context Menu to TabItem in WPF

Continuing the previous post

https://nishantrana.wordpress.com/2012/04/08/creating-dynamic-tabitem-in-wpf/

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.

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

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


public void CloseTabItem(Object sender)
 {
 VMParentForViews vmParentForViews = (sender as MenuItem).DataContext as VMParentForViews;
 this.ObservableCollectionTabItems.Remove(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

https://skydrive.live.com/redir.aspx?cid=2312e1103cbe5ecd&resid=2312E1103CBE5ECD!338&parid=root

Hope it helps


Author: Nishant Rana

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

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

Share your thoughts

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s