web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :

Adding a Close Context Menu to TabItem in WPF

Nishant Rana Profile Picture Nishant Rana 11,325 Microsoft Employee

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


Filed under: WPF Tagged: WPF

This was originally posted here.

Comments

*This post is locked for comments