这些是我的类:
class mainviewmodel { public List<Foo> F { get; set; } public mainviewmodel() { F=new List<Foo>() { new Foo(new Animal(){Name = "Cat"}),new Foo(new Animal(){Name = "Dog"}),new Foo(new Animal(){Name = "Camel"}) }; } } public class Foo { public Animal Animal { get; set; } public Foo(Animal animal) { Animal = animal; } } public class Animal { public string Name { get; set; } }
这是我的MainWindow Xaml代码:
<TabControl ItemsSource="{Binding Path=F}"> <TabControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Animal.Name}"/> </DataTemplate> </TabControl.ItemTemplate> <TabControl.ContentTemplate> <DataTemplate> <TextBlock Text="Something 1"/> </DataTemplate> </TabControl.ContentTemplate> </TabControl>
现在显然我将为List F中的每个项目创建一个TabControl,并且所有TabControl页面都有一个TextBlock Something 1,如下所示:
解决方法
根据以上评论:
为每个Tab创建一个特定的viewmodel类:
public class Tab1: viewmodelBase { //... functionality,properties,etc } public class Tab2: viewmodelBase { //... functionality,etc } public class Tab3: viewmodelBase { //... functionality,etc }
然后为每个创建一个特定的视图(通常以UserControls的形式):
<UserControl x:Class"UserControl1" ...> <!-- UI Elements,etc --> </UserControl> <UserControl x:Class"UserControl2" ...> <!-- UI Elements,etc --> </UserControl> <UserControl x:Class"UserControl3" ...> <!-- UI Elements,etc --> </UserControl>
然后为每个viewmodel类型创建DataTemplates并将这些UserControl放入其中:
编辑:这些应该在Application.Resources下的App.xaml中定义:
<Application ....> <Application.Resources> <DataTemplate DataType="{x:Type local:viewmodel1}"> <local:UserControl1/> </DataTemplate> <DataTemplate DataType="{x:Type local:viewmodel2}"> <local:UserControl2/> </DataTemplate> <DataTemplate DataType="{x:Type local:viewmodel3}"> <local:UserControl2/> </DataTemplate> </Application.Resources> </Application>
最后,放一个ObservableCollection< viewmodelBase>在您的主viewmodel中添加以下项:
public ObservableCollection<viewmodelBase> Tabs {get;set;} //Representing each Tab Item public Mainviewmodel() //Constructor { Tabs = new ObservableCollection<viewmodelBase>(); Tabs.Add(new viewmodel1()); Tabs.Add(new viewmodel2()); Tabs.Add(new viewmodel2()); }