【问题标题】:How to bind WPF TabControl ContentTemplate to an observable collection of different ViewModels如何将 WPF TabControl ContentTemplate 绑定到不同 ViewModel 的可观察集合
【发布时间】:2016-09-21 11:09:23
【问题描述】:

我知道这个问题已经被问过并回答了好几次,但我还是不明白。我似乎缺少了一点理解。

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

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

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

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

谢谢!约翰内斯

【问题讨论】:

    标签: wpf binding tabcontrol


    【解决方案1】:

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

    <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)。

    YourCollection 是对象的混合,如果存在匹配 DataTypeDataTemplate,则每个对象都将根据其类型应用其模板。简单吧?

    【讨论】:

    • 拯救了我的一天。但是魔法很糟糕。如果您不知道如何实现这一点,那么仅通过阅读文档或通过 IntelliSense 搜索,您将永远无法走上正轨。对不起女士,你的文档很烂,还有隐含的魔法。
    猜你喜欢
    • 2010-11-18
    • 1970-01-01
    • 2011-08-04
    • 2013-05-21
    • 2020-12-29
    • 2012-12-10
    • 2015-03-07
    • 1970-01-01
    • 2016-11-08
    相关资源
    最近更新 更多