Question

This question is similar to this question I asked earlier today. The difference is, now I would like to delete a Tab Item referenced by it's name or header. Can I call Remove in a fashion similar to the answer I got on this question?

This is what I've tried:

tabControl.Items.Remove = tabControl.Items //Changes tab according to TreeView
                        .OfType<TabItem>().SingleOrDefault(n => n.Name == stringValue);

Can I use something like this? If so, how?

Was it helpful?

Solution

I don't know much about removing from wpf, however this code is way more likely to work than what you have posted. Remove is a method, you can't assign it a value, so you have to isolate the item you want to remove, check to make sure it isn't null, then pass the object into the Remove method.

var tabToDelete = tabControl.Items.OfType<TabItem>().SingleOrDefault(n => n.Name == stringValue);
if (tabToDelete != null) // Since you chose to use SingleOrDefault, we have to check to make sure it isn't null before we try to remove it.
tabControl.Items.Remove(tabToDelete);

However, I strongly suggest you take a look at WPF - Best way to remove an item from the ItemsSource since it goes into details about checking IF the item CAN be removed, and even if the Remove method is available to that control.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top