WPF: Find if mouse cursor is in a control (not necessarily directly over)
I have a tab control where right clicking on a tab item shows a context menu. When click on a menu item called "Close" I want to close tab item that the user right clicked on.
Here is a problem. If I have TabItem1 and TabItem2 and TabItem1 is selected. T开发者_C百科hen right click on TabItem2 and click "close". At this point, TabItem1 is still selected item but I want to close TabItem2 and i don't know how to get TabItem2.
If I can get if a cursor is in a control (and not directly over b/c it is directly over a TextBlock I added to the tab item header) I would be able to find the control and remove it from Tabcontrol.Items
Any help would be appreciated.
Thanks
Use the ContextMenuOpening event to determine which tab the context menu was opened from, then there is no need to worry about the mouse:
<TabControl TabItem.ContextMenuOpening="ContextMenu_ContextMenuOpening">
<TabControl.Resources>
<ContextMenu x:Key="context_menu" >
<MenuItem Header="Option 1" />
<MenuItem Header="Option 2" />
</ContextMenu>
</TabControl.Resources>
<TabItem x:Name="tab1" Header="Tab 1" Content="This is Tab 1" ContextMenu="{StaticResource context_menu}" />
<TabItem x:Name="tab2" Header="Tab 2" Content="This is Tab 2" ContextMenu="{StaticResource context_menu}" />
</TabControl>
And the event handler:
private void ContextMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
//get the tab item:
TabItem bob = e.Source as TabItem;
}
精彩评论