Question

First of all, this question is a follow up to this question. I feel like I only got half of my question answered.

As well as deleting tabItems referenced by Name, I also need to be able to delete tabItems by referencing their Headers.

When implementing my answer and changing n.Name to n.Header, like so:

var tabToDelete = tabControl.Items.OfType<TabItem>().SingleOrDefault(n => n.Header == stringValue);
if (tabToDelete != null) 
tabControl.Items.Remove(tabToDelete);

I find that it does not work the same. Should this work, or do I need to edit this whole structure? If so how would I do that to make sure the tabItem I need is referenced by Header?

Addition: When the tabs referenced by Name are deleted, they are taken off of the screen, whereas the tabs reference by Header are not (until you manually switch tabs). This leads me to think that they are still existing in the program.

Was it helpful?

Solution

Your problem is that Header is an object and not a string. You're comparing the two values as if they are, but because Header is an object you're actually doing a reference comparison, not a value comparison. You need to cast Header to a string by simply calling .ToString() on Header.

var tabToDelete = tabControl.Items.OfType<TabItem>().SingleOrDefault(n => (n.Header as string) == stringValue);
if (tabToDelete != null)
    tabControl.Items.Remove(tabToDelete);

If this doesn't solve the problem you can force the control to redraw by calling

tabControl.Refresh();

Update

Credit to Daniel Gimenez for spotting the possible null reference exception. The issue of the Header being set to a control is not a problem however, as all objects can call ToString(), the real problem is if the Header is not set at all, resulting in a null object.

OTHER TIPS

Like Ryan said, the problem is that Header can be a control instead of just text. If Header can be null, as String or Convert.ToString() will be better than toString() because they can both handle converting from null values whereas ToString() produces an exception.

Using Convert.ToString() might be overkill, but if your Headers are bound to values that can't implicitly convert to strings, such as integers, then using Convert.ToString() will be able to handle them. Also this solution will handle the case if multiple items with the same header value exist.

private void RemoveTabByHeader(string str) 
{
    TabsMain.Items.OfType<TabItem>().Where(t => Convert.ToString(t.Header) == str)
       .ToList().ForEach(t => TabsMain.Items.Remove(t));
}

This is tested. The TabControl correctly updates.

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