2

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

H.B.
  • 166,899
  • 29
  • 327
  • 400
Luke
  • 2,434
  • 9
  • 39
  • 64

1 Answers1

3

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.

Keith Pinson
  • 7,835
  • 7
  • 61
  • 104
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • What was I thinking!?!? How did I miss that. I thought it said TabItem. DUURRR – Luke Sep 01 '11 at 14:54
  • @Luke: If you need help obtaining the tab, let me know. – H.B. Sep 01 '11 at 14:56
  • Okay... Now I have a genuine issue. – Luke Sep 01 '11 at 14:58
  • I really need to think about these things more. I think I know the problem. – Luke Sep 01 '11 at 15:15
  • I have fixed it. You can't remove from the items collection using just an index... oh, yes I can. RemoveAt() is what I wanted. – Luke Sep 01 '11 at 15:16
  • @Luke: I added a suggestion of how to get the tab to my answer. – H.B. Sep 01 '11 at 15:28
  • That's a lot better, thanks. I am still relatively new to WPF, so I don't yet know about everything that can be used. – Luke Sep 01 '11 at 15:33
  • @Luke: Actually even better might be using [commands](http://msdn.microsoft.com/en-us/library/ms752308.aspx) and passing the `TabItem` as `CommandParameter` in XAML. As you are new to WPF you might find [all the articles on MSDN](http://msdn.microsoft.com/en-us/library/ms754130.aspx) to be useful. – H.B. Sep 01 '11 at 15:38