c# – 当TabControl的ItemsSource绑定到WPF中的列表时,如何设计TabPage?

这些是我的类:
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,如下所示:

我想要的只是设计其中一个页面.比如在名为Something 3的Camel页面添加新按钮.

解决方法

根据以上评论

为每个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());
}

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么