How to: Create a TabControl That Has ContextMenus
This topic discusses how to create a TabControl and attach a ContextMenu to each TabItem. When a user clicks on an item in the ContextMenu, the TabItem must handle the Click event. The handler can be added to the ContextMenu items, but you must know what the target of the ContextMenu item is for the appropriate action to be taken.
The following example shows how to do this. The first example creates a TabItem and attaches a ContextMenu to the TabItem.
Example
<TabItem Name="backgroundcolor" Header="Choose a Background Color">
<TabItem.ContextMenu>
<ContextMenu MenuItem.Click="MyMenuHandler">
<MenuItem Header="Red" Name="red"/>
<MenuItem Header="Blue" Name="blue"/>
<MenuItem Header="Yellow" Name="yellow"/>
</ContextMenu>
</TabItem.ContextMenu>
<TabItem.Content>Some content about background colors.</TabItem.Content>
</TabItem>
The second example shows how to make a handler to handle the Click event calls.
void MyMenuHandler(object sender, RoutedEventArgs e)
{
ContextMenu cm = (ContextMenu)sender;
target = cm.PlacementTarget;
if(e.Source==red)
{
backgroundcolor.Background = Brushes.Red;
backgroundcolor.Header = "Background red";
}
else if(e.Source==blue)
{
backgroundcolor.Background = Brushes.LightBlue;
backgroundcolor.Header = "Background blue";
}
else if(e.Source==yellow)
{
backgroundcolor.Background = Brushes.Yellow;
backgroundcolor.Header = "Background yellow";
}
}
Notice that to find the target of the ContextMenu, you can use the code in the previous example or the following.
ContextMenu cm = (ContextMenu)ContextMenu.ItemsControlFromItemContainer ((MenuItem)e.OriginalSource);
UIElement placementTarget = cm.PlacementTarget;