Wpf 将TabControl绑定到具有不同内容的ObservableCollection
'我正在尝试创建w mainwindow,该窗口将有一个包含多个项的tabcontrol(每个项仅在需要时显示)。。。假设我们有A型物品,B型物品和C型物品 我希望(使用MVVM模式)有一个可观察的对象集合,这些对象表示我的tabitems,并且与我的UsersControl相关(每个tabitem都是usercontrol)。。。 问题是我不知道怎么做 我有一个TabItemViewModel基类:Wpf 将TabControl绑定到具有不同内容的ObservableCollection,wpf,binding,observablecollection,tabcontrol,Wpf,Binding,Observablecollection,Tabcontrol,'我正在尝试创建w mainwindow,该窗口将有一个包含多个项的tabcontrol(每个项仅在需要时显示)。。。假设我们有A型物品,B型物品和C型物品 我希望(使用MVVM模式)有一个可观察的对象集合,这些对象表示我的tabitems,并且与我的UsersControl相关(每个tabitem都是usercontrol)。。。 问题是我不知道怎么做 我有一个TabItemViewModel基类: public class TabItemViewModelBase : ViewModelB
public class TabItemViewModelBase : ViewModelBase
{
//Fields :
RelayCommand _closeCommand;
//Constructor:
public TabViewModel(string header)
{
this.Header = header;
}
}
在我的主窗口数据上下文中,我有一个此类的可观察集合:
//Propriétés
ObservableCollection<TabViewModel> _tabItems;
//Propriétés
可观察的收集项目;
在我的主窗口中,TabControl项有以下标记
<TabControl Padding="0" ItemsSource="{Binding Path=Workspaces}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
**<view:ClientView/>**
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
****
但正如您所看到的,所有项目都附加到ClientView用户控件,我正在使用tabviewitem创建项目,我需要一个属性或方法来指定observablecollection每个元素的内容形式
(我有一个ClientListingViewModel类和ClientCreationViewModel类),但我不能同时使用这两个类,因为我不知道如何为它们中的每一个指定视图
谢谢 要指定针对特定视图模型的视图,可以在datatemplate中执行此操作 首先,需要向视图和viewmodel名称空间添加名称空间引用。我已经包含了一个使用窗口的示例,但它也适用于用户控件
<Window ...
xmlns:v="clr-namespace:PutYourViewNamespaceHere"
xmlns:vm="clr-namespace:PutYourViewModelNamespaceHere">
接下来,您需要在容器的参考资料部分中定义datatemplates。
在下面的示例中,我使用ClientListingView作为ClientListingViewModel的数据模板
<Window.Resources>
<DataTemplate DataType="{x:Type vm:ClientListingViewModel">
<v:ClientListingView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:ClientCreationViewModel">
<v:ClientCreationView />
</DataTemplate>
</Window.Resources>
要指定针对特定视图模型的视图,可以在datatemplate中执行此操作 首先,需要向视图和viewmodel名称空间添加名称空间引用。我已经包含了一个使用窗口的示例,但它也适用于用户控件
<Window ...
xmlns:v="clr-namespace:PutYourViewNamespaceHere"
xmlns:vm="clr-namespace:PutYourViewModelNamespaceHere">
接下来,您需要在容器的参考资料部分中定义datatemplates。
在下面的示例中,我使用ClientListingView作为ClientListingViewModel的数据模板
<Window.Resources>
<DataTemplate DataType="{x:Type vm:ClientListingViewModel">
<v:ClientListingView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:ClientCreationViewModel">
<v:ClientCreationView />
</DataTemplate>
</Window.Resources>
Small notice-最好将DataTempalates声明放在App.Xaml中,或放在App.Xaml中合并的任何资源文件中。它应该会为您节省一些内存(特别是在usercontrols的情况下)。问题是viewModel部分位于另一个库中,当我尝试在XML文件中引用它时,我无法访问所有viewModel类(要执行{x:Type vm:ClientListingViewModel),我只能访问viewModel的一个类(这是一个引用问题!)感谢looot!小提示-最好将DataTempalates声明放在App.Xaml中,或放在App.Xaml中合并的任何资源文件中。这样可以节省一些内存(特别是在使用用户控件的情况下)问题是viewModel部分位于另一个库中,当我尝试在XML文件中引用它时,我无法访问所有viewModel类(要执行{x:Type vm:ClientListingViewModel),我只能访问viewModel的一个类(这是一个引用问题!),感谢Looot!