Sam
Sam

Reputation: 29009

Load TabItem content when it is selected (not before) in MVVM

In a Prism V4 / MEF / MVVM app, I got a View containing a TabControl.

In the first TabItem I show a list of items, the second TabItem is disabled unless a valid item is selected. Now when the user clicks on the second TabItem I want to load and prepare some additional data into the second TabItem.

How Do I get notice of TabItem changes in MVVM?

Upvotes: 2

Views: 5016

Answers (1)

vortexwolf
vortexwolf

Reputation: 14037

I think you mean lazy loading. Launch this example and put debug breakpoint into the ContentViewModel constructor.

public MainWindow()
    {
        InitializeComponent();
        var items = new List<TabItemViewModel>
        { new TabItemViewModel{Title="Tab 1", Content = new Lazy<ContentViewModel>(() => new ContentViewModel(1))},
            new TabItemViewModel{Title="Tab 2", Content = new Lazy<ContentViewModel>(() => new ContentViewModel(2))}
        };
        tab.ItemsSource = items;
    }

    public class TabItemViewModel
    {
        public string Title { get; set; }
        public Lazy<ContentViewModel> Content { get; set; }
    }

    public class ContentViewModel
    {
        public ContentViewModel(int i)
        {
            this.SomeText = "Loaded tab "+i;
        }
        public string SomeText { get; set; }
    }

Xaml templates:

    <TabControl x:Name="tab">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Title}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Content.Value.SomeText}"/>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>

Upvotes: 6

Related Questions