WPF C# Programmatically adding and moving tabs

SumGuy picture SumGuy · Feb 11, 2011 · Viewed 17.1k times · Source

I'm currently working on something that is probably done in plenty of examples out there. But after some searching I can't find anything.

I'm working with WPF tab control and I'm trying to recreate some basic functionality (which you see in all internet browsers nowadays) to add a new tab by clicking a '+' tab which is the last listed tab.

I already have the '+' tab which adds a new tab. My problem is, I want to move the '+' tab after the new tab (so its the end tab again) and switch view to the new tab that has just been created.

I thought something like:

    void tiNewTab_Add(object sender, EventArgs e)
    {
        int idx = tabControl1.Items.Count;
        tabControl1.SelectedIndex = idx - 1;
        TabItem ti = new TabItemKPI();
        tabControl1.Items.Add(ti);
        tabControl1.Items.MoveCurrentToLast();
    }

...would work but no luck :(

Answer

HCL picture HCL · Feb 11, 2011

Try something like this:

tabControl1.Items.Insert(tabControl1.Items.Count-1,ti); 

This will do because you always have at least one TabItem (the + one)

Then select the second last one by

tabControl1.SelectedIndex=tabControl1.Items.Count-2;