延迟加载WPF选项卡的内容选项卡、加载、内容、WPF

2023-09-02 20:47:33 作者:繁花黎落、诉不尽哀思惆怅

我的WPF应用程序被组织成包含不同屏幕的每个选项卡中的TabControl。

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

一个TabItem的绑定到数据需要一点时间来加载。由于这TabItem的重新presents一个屏幕,用户只能很少使用,我想不会加载数据,直到用户选择该选项卡。

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?

推荐答案

标签控制的工作方式有两种,

Tab control works two ways,

当我们明确添加选项卡项目,每个标签项目被加载并初始化立即含有每一件事情。 当我们绑定的ItemsSource的项目清单,我们为每个数据项不同的数据模板,标签控件将只创建一个内容视图中选择数据项,只有当标签项目被选中,装内容视图的事件将被解雇和内容将被加载。当不同的标签项中选择卸载事件将被解雇pviously选择$ P $内容视图和装将被解雇的新选择的数据项。

使用第二方法是有点复杂,但在运行时它肯定会减少它正在使用的资源,但在切换片时间,它可能是慢一点一会儿。

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;}
}

和您必须创建列表TabItemData或数组,你必须设置的TabControl的项目源列出/ TabItemData的数组。

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

然后创建的TabControl的ItemTemplate中的数据模板绑定标题属性。

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

然后创建创建的TabControl中的ContentTemplate含有ContentControl中使用的ResourceKey属性找到资源键的ContentTemplate数据模板。

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