简体   繁体   English

TabControl WPF MVVM中的延迟加载(仍然)

[英]Lazy loading in TabControl WPF MVVM (yet, again)

I know, that this topic has been discussed many times , so straight to the point. 我知道,这个话题已经讨论了很多 ,直截了当。

This is the ItemsSource of TabControl : 这是TabControlItemsSource

Tabs = new ObservableCollection<aTabViewModel>
{
    new HomeViewModel(),
    new StatisticsViewModel()
};

Here is the TabControl itself 这是TabControl本身

<TabControl ItemsSource="{Binding Tabs}">
<TabControl.Resources>
    <DataTemplate DataType="{x:Type pagesVM:HomeViewModel}">
        <pages:Home/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type pagesVM:StatisticsViewModel}">
        <pages:Statistics/>
    </DataTemplate>
</TabControl.Resources>

<TabControl.ItemContainerStyle>
    <Style BasedOn="{StaticResource MetroTabItem}" TargetType="TabItem">
        <Setter Property="Header" Value="{Binding Header}" />
    </Style>
</TabControl.ItemContainerStyle>

HomeViewModel and StatisticsViewModel are instantiated first time when we add them to Tabs collection, and second time when we select tab in a application (which is seems to be a behaviour of TabControl ). 第一次将HomeViewModelStatisticsViewModel实例化时,将它们添加到Tabs集合中,而第二次当我们在应用程序中选择tab时被实例化(这似乎是TabControl的行为)。 And this double-loading apparently isn't right thing. 而且这种双重加载显然不是正确的事情。

Q: How can I make my tabs load only when selected? 问:如何使我的标签页仅在选中时加载?

How can I make my tabs load only when selected? 如何使我的标签页仅在选中时加载?

Put in such load logic in the GotFocus event on the tab page with checks to verify that the DataContext is only loaded once. 在选项卡页的GotFocus事件中放入此类加载逻辑,并进行检查以验证DataContext仅加载一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM