如何将WPF TabControl ContentTemplate绑定到不同ViewModel的可观察集合

时间:2016-05-24 09:54:08

标签: wpf binding tabcontrol

我知道这个问题已经被问过几次了,但我仍然没有得到它。我似乎错过了一点理解。

我有一个TabControl绑定到一个可观察的视图模型列表。当然,视图模型可以是不同的类型,从相同的基类型派生。当视图模型添加到列表中时,我希望tabcontrol根据视图模型的类型添加新的标签页。

我不明白如何设置TabControl的ContentTemplate以根据视图模型的类型选择正确的视图。

可以在这里找到一个基本的例子,但是我没有使用动态视图来运行它:

How to bind items of a TabControl to an observable collection in wpf?

谢谢!约翰内斯

1 个答案:

答案 0 :(得分:3)

好的,我将修改您链接的答案中的示例代码:

<Window.Resources>
    <DataTemplate x:Key="templateForTheHeader" DataType="{x:Type vm:BaseViewModel}">
        <TextBlock Text="{Binding CommonPropertyToDisplayInTheHeader}"/>
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:ViewModel1}">
        <TextBlock Text="{Binding PropertyInVM1}"/>
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:ViewModel2}">
        <TextBlock Text="{Binding PropertyInVM2}"/>
    </DataTemplate>
</Window.Resources>

...

<TabControl ItemsSource="{Binding YourCollection}"
            ItemTemplate="{StaticResource templateForTheHeader}">
</TabControl>

标头显示基本VM类中的一些属性。 重要的是,我删除了其他DataTemplates的x:key,这将使其应用于DataTypeWindow中找到的已定义ContentTemplate的每个实例。不需要TabControl

YourCollection是一个混合对象,如果存在匹配DataTemplate的{​​{1}},则每个对象都会根据其类型获取其模板。简单呃?