show context menu only on tabcontrol
I am trying to add a context menu that has "Close" and "Close all but this" like in IE8. This menu should be displayed when I click on the tab but not on开发者_JAVA百科 tabitem.
How can i do this?
I believe you want the ContextMenu to appear only when user clicks on the Header of TabItem and not the content area of the TabControl.
If so, you can define a template for Header. See sample code below.
Note:
- The Context menu will appear only when you click on the text part (and not rest of the blank area) of the TabItem Header. If you want for the whole Tab Header area, you will need to modify the ControlTemplate for TabItem.
Sample Code:
<Window x:Class="WpfApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<DataTemplate x:Key="tabHeaderTemplate">
<ContentPresenter Width="Auto" Content="{TemplateBinding Content}">
<ContentPresenter.ContextMenu>
<ContextMenu>
<MenuItem Header="Close Tab" />
<MenuItem Header="Close Other Tabs" />
<Separator />
<MenuItem Header="New Tab" />
</ContextMenu>
</ContentPresenter.ContextMenu>
</ContentPresenter>
</DataTemplate>
</Window.Resources>
<Grid>
<TabControl>
<TabItem Header="Tab 1"
HeaderTemplate="{StaticResource tabHeaderTemplate}">
<Label>Data for first Tab goes here</Label>
</TabItem>
<TabItem Header="Tab 2"
HeaderTemplate="{StaticResource tabHeaderTemplate}">
<Label>Data for second Tab goes here</Label>
</TabItem>
<TabItem Header="Tab 3">
<Label>Data for third Tab goes here</Label>
</TabItem>
</TabControl>
</Grid>
</Window>
Is this what you need:
Code:
<TabControl Margin="28,25,57,38" Name="tabControl1">
<TabItem Header="tabItem1" Name="tabItem1">
<TabItem.ContextMenu>
<ContextMenu Name="ct1" >
<MenuItem Name="Item1" Header="Close"/>
<MenuItem Name="Item2" Header="CloseOtherThankThis" />
</ContextMenu>
</TabItem.ContextMenu>
<Grid>
<Label Margin="41,75,22,64" Name="label1">First Tab</Label>
</Grid>
</TabItem>
<TabItem Header="tabItem2" Name="tabItem2">
<TabItem.ContextMenu>
<ContextMenu Name="ct2">
<MenuItem Name="Item3" Header="Close"/>
<MenuItem Name="Item4" Header="CloseOtherThankThis" />
</ContextMenu>
</TabItem.ContextMenu>
</TabItem>
</TabControl>
Are you talking about the case in which there should be no duplicate context menu?
精彩评论