Stanley Russian
Stanley Russian

Reputation: 73

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:

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

Here is the TabControl itself

<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). And this double-loading apparently isn't right thing.

Q: How can I make my tabs load only when selected?

Upvotes: 1

Views: 1266

Answers (1)

ΩmegaMan
ΩmegaMan

Reputation: 31616

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.

Upvotes: 2

Related Questions