这不是MVVM。您不应该在视图模型中创建UI元素。
您应该将Tab的ItemsSource绑定到ObservableCollection,并且该模型应包含带有应创建的选项卡信息的模型。
这是代表选项卡页面的VM和模型:
public sealed class ViewModel{ public ObservableCollection<TabItem> Tabs {get;set;} public ViewModel() { Tabs = new ObservableCollection<TabItem>(); Tabs.Add(new TabItem { Header = "One", Content = "One's content" }); Tabs.Add(new TabItem { Header = "Two", Content = "Two's content" }); }}public sealed class TabItem{ public string Header { get; set; } public string Content { get; set; }}这是绑定在窗口中的外观:
<Window x:Class="WpfApplication12.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <ViewModel xmlns="clr-namespace:WpfApplication12" /> </Window.DataContext> <TabControl ItemsSource="{Binding Tabs}"> <TabControl.ItemTemplate> <!-- this is the header template--> <DataTemplate> <TextBlock Text="{Binding Header}" /> </DataTemplate> </TabControl.ItemTemplate> <TabControl.ContentTemplate> <!-- this is the body of the TabItem template--> <DataTemplate> <TextBlock Text="{Binding Content}" /> </DataTemplate> </TabControl.ContentTemplate> </TabControl></Window>(请注意,如果要在不同的选项卡中使用不同的内容,请使用
DataTemplates。每个选项卡的视图模型应该是其自己的类,或者创建一个自定义
DataTemplateSelector来选择正确的模板。)
数据模板内部的UserControl:
<TabControl ItemsSource="{Binding Tabs}"> <TabControl.ItemTemplate> <!-- this is the header template--> <DataTemplate> <TextBlock Text="{Binding Header}" /> </DataTemplate> </TabControl.ItemTemplate> <TabControl.ContentTemplate> <!-- this is the body of the TabItem template--> <DataTemplate> <MyUserControl xmlns="clr-namespace:WpfApplication12" /> </DataTemplate> </TabControl.ContentTemplate></TabControl>


