tags:

views:

59

answers:

2

My WPF application is organized as a TabControl with each tab containing a different screen.

One TabItem is bound to data that takes a little while to load. Since this TabItem represents a screen that users may only rarely use, I would like to not load the data until the user selects the tab.

How can I do this?

A: 

You could look at the SelectionChanged event:

http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selectionchanged.aspx

That will be called when the selected tab is changed; depending on whether your tabs are created through a binding to a collection or not (this works best if 'not'), it could be as simple as creating an instance of a UserControl containing all the controls you want for the page, then adding it to some Panel (for example, a Grid) that exists as a placeholder on that tab.

Hope that helps!

Kieren Johnstone
+2  A: 

Tab control works two ways,

  1. When we add Tab Items explicitly, each tab item is loaded and initialized immediately containing every thing.
  2. When we bind ItemsSource to list of items, and we set different data template for each data item, tab control will create only one "Content" view of selected data item, and only when the tab item is selected, "Loaded" event of content view will be fired and content will be loaded. And when different tab item is selected, "Unloaded" event will be fired for previously selected content view and "Loaded" will be fired for new selected data item.

Using 2nd method is little complicated, but at runtime it will certainly reduce the resources it is using, but at time of switching tabs, it may be little slower for a while.

You have to create custom data class as following

class TabItemData{
   public string Header {get;set;}
   public string ResourceKey {get;set;}
   public object MyBusinessObject {get;set;}
}

And you must create list or array of TabItemData and you must set TabControl's items source to list/array of TabItemData.

Then create ItemTemplate of TabControl as data template binding "Header" property.

Then create create ContentTemplate of TabControl as data template containing ContentControl with ContentTemplate of Resource key found in ResourceKey property.

Akash Kava
+1 You will use the second option naturally if you're doing MVVM.
Kent Boogaart
Will using the second option cause the tabs to lose state when they are unloaded?
Bear
Yes, but you can use properties in MyBusinessObject to define state that can be synchronized with visual state and any other logical state of control.
Akash Kava