如何将 WPF TabControl ContentTemplate 绑定到不同 ViewModel 的可观察集合
How to bind WPF TabControl ContentTemplate to an observable collection of different ViewModels
我知道这个问题已经被问过和回答过好几次了,但我还是不明白。好像少了一个理解
我有一个 TabControl 绑定到一个可观察的视图模型列表。当然,viewmodel 可以是不同类型,派生自相同的基本类型。当将视图模型添加到列表时,我希望 tabcontrol 根据视图模型的类型添加一个新的标签页。
我不明白如何设置 TabControl 的 ContentTemplate 以根据视图模型的类型选择正确的视图。
一个基本的例子可以在这里找到,但我没有得到它和运行动态视图:
How to bind items of a TabControl to an observable collection in wpf?
谢谢!约翰内斯
好的,我将修改您链接的答案中的示例代码:
<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>
header 在基本 VM class 中显示一些 属性。
重要的是,我删除了其他数据模板的 x:key
,这将使它应用于 Window
中定义的 DataType
的每个实例(ContentTemplate
TabControl
不需要)。
YourCollection
是 objects 的混合,如果 DataTemplate
与匹配的 DataType
存在,则每个模板都将根据其类型应用其模板。简单吗?
我知道这个问题已经被问过和回答过好几次了,但我还是不明白。好像少了一个理解
我有一个 TabControl 绑定到一个可观察的视图模型列表。当然,viewmodel 可以是不同类型,派生自相同的基本类型。当将视图模型添加到列表时,我希望 tabcontrol 根据视图模型的类型添加一个新的标签页。
我不明白如何设置 TabControl 的 ContentTemplate 以根据视图模型的类型选择正确的视图。
一个基本的例子可以在这里找到,但我没有得到它和运行动态视图:
How to bind items of a TabControl to an observable collection in wpf?
谢谢!约翰内斯
好的,我将修改您链接的答案中的示例代码:
<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>
header 在基本 VM class 中显示一些 属性。
重要的是,我删除了其他数据模板的 x:key
,这将使它应用于 Window
中定义的 DataType
的每个实例(ContentTemplate
TabControl
不需要)。
YourCollection
是 objects 的混合,如果 DataTemplate
与匹配的 DataType
存在,则每个模板都将根据其类型应用其模板。简单吗?