如何将WPF TabControl ContentTemplate绑定到不同ViewModel的可观察集合 [英] How to bind WPF TabControl ContentTemplate to an observable collection of different ViewModels

查看:169
本文介绍了如何将WPF TabControl ContentTemplate绑定到不同ViewModel的可观察集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经被问过并回答过几次了,但我还是不明白.我似乎缺少某种了解.

I know this question has been asked and answered several times already but I still don't get it. I seem to be missing a piece of understanding.

我有一个TabControl绑定到一个可观察的viewmodel列表.当然,视图模型可以是不同的类型,它们是从相同的基本类型派生的.当将视图模型添加到列表中时,我希望tabcontrol根据视图模型的类型添加一个新的选项卡页.

I have a TabControl bound to an observable list of viewmodels. The viewmodels can be of different types, derived from the same base type, of course. When a viewmodel is added to the list I want the tabcontrol adds a new tabpage based on the type of the view model.

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

I do not understand how to set up the ContentTemplate of the TabControl to pick the right view based on the type of the view model.

可以在此处找到一个基本示例,但我没有使用动态视图启动它并运行它:

A Basic example can be found here, but I do not get it up and running with dynamic views:

如何绑定在wpf中将TabControl的项目添加到可观察的集合中?

谢谢!约翰内斯

推荐答案

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

Ok, i will modify the sample code in the answer you linked:

<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 ,这将使其应用于在 Window中找到的已定义 DataType 的每个实例.(不需要 TabControl 中的 ContentTemplate ).

The header displays some property in the base VM class. And the important thing, i removed the x:key of the other DataTemplates, this will make it being applied to every instance of the defined DataType found in the Window (ContentTemplate in the TabControl not needed).

YourCollection 是对象的混合,如果存在与 DataType 匹配的 DataTemplate ,则每个对象都会根据其类型应用模板.简单吗?

YourCollection is a mix of objects, each of it will get its template applied based on its type if a DataTemplate with matching DataType exists. Simple uh?

这篇关于如何将WPF TabControl ContentTemplate绑定到不同ViewModel的可观察集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆