Search code examples
c#wpfheadertabitem

Delete a Tab Item based off of its header


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.


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.