如何在TabControl的ItemsSource绑定到WPF中的列表时设计TabPage?

时间:2013-07-30 16:20:09

标签: c# .net wpf xaml tabcontrol

这些是我的课程:

   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>

现在很明显,我会为列表TabControl中的每个项目设置F一个页面,所有TabControl页面都有TextBlock Something 1 < / em>如下所示:

enter image description here

我想要的只是设计其中一个页面。比如将新的button添加到名为 Something 3 的Camel页面。

1 个答案:

答案 0 :(得分:6)

根据上述评论:

为每个标签创建一个特定的ViewModel类:

public class Tab1: ViewModelBase
{
   //... functionality, properties, etc
}

public class Tab2: ViewModelBase
{
   //... functionality, properties, etc    
}

public class Tab3: ViewModelBase
{
   //... functionality, properties, 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并将这些UserControls放入其中:

修改:这些内容应在App.xaml Application.Resources下的<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()); } 并添加以下项目:

{{1}}