Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

.net - Lazy loading WPF tab content

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...