I have a tab control in a window. The tabs all have simple context menus which (are supposed to) allow the user to close them. However, when I click close, nothing happens.
Here is the event handler
void closeTab_Click(开发者_JAVA技巧object sender, RoutedEventArgs e)
{
Tabs.Items.Remove((MenuItem)sender);
}
I've looked around about closing tabs, but none of the articles I found went into much detail about how to actually close the tab.
New problem:
void closeTab_Click(object sender, RoutedEventArgs e)
{
MenuItem close = (MenuItem)sender;
Tabs.Items.Remove(Convert.ToInt32(close.Name.Remove(0,3)));
}
The context menu item is named thusly:
Name = "Tab" + Tabs.Items.Count.ToString(),
It still does nothing
The menu item is not the tab. You cannot remove it from the TabControl
. You need a reference to the tab to which the MenuItem
belongs. This can be done in various ways.
I see you tried some rather hacky things there with names and string manipulation, here would be a more clean approach which does not require any of that:
var target = (FrameworkElement)sender;
while (target is ContextMenu == false)
target = (FrameworkElement)target.Parent;
var tabItem = (target as ContextMenu).PlacementTarget;
Tabs.Items.Remove(tabItem);
This gets the parent until it finds the ContextMenu
and gets the TabItem
from the PlacementTarget
.
精彩评论