Lazy loading WPF tab content

Viewed 22261

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?

7 Answers

I found a much simpler way. Simply wait to initialize the ViewModel until the tab is activated.

public int ActiveTab
{
    get
    {
        return _ActiveTab;
    }
    set
    {
        _ActiveTab = value;
        if (_ActiveTab == 3 && InventoryVM == null) InventoryVM = new InventoryVM();
    }
}

A quick and simple Data-centric solution would be to set DataContext by style when the tab IsSelected

<Style TargetType="{x:Type TabItem}">
    <Setter Property="DataContext" Value="{x:Null}"/> <!--unset previous dc-->
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="DataContext" Value="{Binding LazyProperty}"/>
        </Trigger>
    </Style.Triggers>
</Style>

where LazyProperty is a property using some of the lazy load patterns, for example:

private MyVM _lazyProperty;
public MyVM LazyProperty => _lazyProperty ?? (_lazyProperty = new MyVM());
Related