Closing/Removing a tab item WPF

三世轮回 提交于 2019-12-22 17:59:34

问题


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(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


回答1:


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.



来源:https://stackoverflow.com/questions/7272084/closing-removing-a-tab-item-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!