Dynamically created tabs in tabcontrol disappear when F5 is pressed

Dec 15, 2009 at 4:06 PM

Hello,

I have a tabcontrol that contains a list in the first tab, when a row is doubleclicked a new tab is created with the "details" of the item on that row.

Several tabs can be opened, although only one tab per row.

My problem is that when someone press F5 to update the page in the browser, these dynamically created tabs disappear.

I'm rather new to the WPF world so I have no clue to whats going on, any tips and ideas what I can start looking for?

 

/Rob

Coordinator
Dec 16, 2009 at 1:42 AM

Rob,

I am assuming you are using Xbap. In Xbaps, when you press F5 it re-creates the whole app again. As a result you will lose all the Tabs created at Runtime. Do a MessageBox.Show() in the page constructor, and you will notice that it gets called whenever you press F5. You might what to Persistent the current state of the tabs and use it while re-loading.

Hope this helps,

Navin

Dec 16, 2009 at 7:32 AM

Hello,

Yes I'm using xbap.

I figured it would be something like that... same as in ASP.NET.

Do I have to save all my dynamic controls and recreate them in the constructor ( as in ASP.NETs PageLoad )? Or is there som other trick I can use.

Thanks for the fast reply.

/Rob

Dec 18, 2009 at 8:51 AM

This is how I solved it, figured it could help others woth the same problem.

1. I created a property of type List<TabItem> called "DynamicTabs" in the App.xaml.cs

2. Everytime I add/remove a tab to the tabcontrol I also add/remove it from this list.

 

//Save dynamic tab				
((App)Application.Current).DynamicTabs.Add(MyTabItem);

//Remove dynamic tab				
((App)Application.Current).DynamicTabs.Remove(MyTabItem);

 

3. I added eventhandlers forwhen the tabcontrol is unloaded and loaded. Found out that I had to remove all the tabs at unloading, otherwise they already had a parent when I tried to add them again in the loaded event. I also tagged the tab that was focused so I can focus it again when reloading.

 

private void tabCtrl_Unloaded(object sender, RoutedEventArgs e)
{
	//Find out which tab is selected, and tag it
	TabControl tc = (TabControl)sender;
	int selected = tc.SelectedIndex;
	((TabItem)tc.Items[selected]).Tag = "FOCUSED";

	//Remove dynamically created tabs from parentcontrol
	foreach (TabItem ti in ((App)Application.Current).DynamicTabs)
	{
		tabCtrl.Items.Remove(ti);
	}
}
//*****************************************************************************************
private void tabCtrl_Loaded(object sender, RoutedEventArgs e)
{
	if (((App)Application.Current).DynamicTabs.Count != 0)
	{
		//Add dynamically created tabs from parentcontrol
		foreach (TabItem ti in ((App)Application.Current).DynamicTabs)
		{
			tabCtrl.Items.Add(ti);
			if ((String)ti.Tag == "FOCUSED")
			{
				ti.Tag = String.Empty;
				ti.Focus();
			}
		}				
	}
}