在MVVM中选择(而不是之前)时加载TabItem内容

时间:2010-11-25 10:39:39

标签: wpf mvvm prism

在Prism V4 / MEF / MVVM应用程序中,我得到了一个包含TabControl的视图。

在第一个TabItem中,我显示了一个项目列表,除非选择了有效项目,否则将禁用第二个TabItem。现在,当用户点击第二个TabItem时,我想加载并准备一些额外的数据到第二个TabItem。

如何了解MVVM中的TabItem更改?

1 个答案:

答案 0 :(得分:6)

我认为你的意思是延迟加载。启动此示例并将调试断点放入ContentViewModel构造函数中。

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模板:

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