我知道这个问题已经被问过并回答过几次了,但我还是不明白。我似乎缺少某种了解。
我有一个TabControl绑定到一个可观察的viewmodel列表。当然,视图模型可以是不同的类型,它们是从相同的基本类型派生的。当将视图模型添加到列表中时,我希望tabcontrol根据视图模型的类型添加一个新的选项卡页。
我不明白如何设置TabControl的ContentTemplate来根据视图模型的类型选择正确的视图。
可以在这里找到一个基本示例,但是我没有使用动态视图来启动它并运行它:
如何将TabControl的项目绑定到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>
标头显示基本VM类中的某些属性。重要的是,我删除了x:key
其他DataTemplates,这将使它应用于(在不需要的地方)DataType
在Window
(例如)中找到的定义的每个实例。ContentTemplate
TabControl
YourCollection
为对象的混合,每个将获得它的模板应用了基于它的类型,如果DataTemplate
有匹配的DataType
存在。简单吧?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句