如何基于ContentControl当前内容的数据类型自动使用DataTemplate [英] How to Automatically Use a DataTemplate Based on ContentControl's Current Content's DataType
问题描述
当我尝试指定一个ContentControl使用多个DataTemplate以便使用正确的(基于Type)一个DataTemplate时,我最终得到的Content只是Content的ToString()值。
When I attempt to specify multiple DataTemplates for use by a ContentControl so that the correct one (based on Type) is used, I end up with Content that is simply the Content's ToString() value.
<ContentControl DataContext="{Binding MyTreeRootViewModels}" Content="{Binding /, Path=CurrentlySelectedTreeViewModel}">
<ContentControl.Resources>
<DataTemplate DataType="x:Type vm:TypeAViewModel">
<StackPanel>
<local:TypeAUserControl />
</StackPanel>
</DataTemplate>
<DataTemplate DataType="x:Type vm:TypeBViewModel">
<StackPanel>
<local:TypeBUserControl />
</StackPanel>
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
在上面的示例中,当我看到一个TypeAViewModel的树节点时,会显示 MyApp.ViewModel.TypeAViewModel由CurrentSelectedTreeViewModel返回。我希望看到我的TypeAViewModelUserControl。
In the example above I would see "MyApp.ViewModel.TypeAViewModel" displayed when a tree node of TypeAViewModel is returned by CurrentlySelectedTreeViewModel. I expect to see my TypeAViewModelUserControl.
我尝试放置一个< TextBlock Text = TESTING />我的一个DataTemplates元素中的元素只是为了查看问题是否与我的用户控件有关。结果相同。
I've tried putting a single <TextBlock Text="TESTING"/> element in one of my DataTemplates just to see if the problem was related to my user controls. Same result.
有什么想法我做错了吗?
Any ideas what I am doing wrong?
(顺便说一下,CurrentlySelectedTreeViewModel是一个属性,它返回树视图中当前选定的节点。它似乎工作得很好-当我在树中选择节点时,该节点的正确类型名称将显示为ContentControl。)
(By the way, the CurrentlySelectedTreeViewModel is a property that returns the currently selected node in my treeview. It seems to work just fine - as I select nodes in the tree, the correct type name for the node appears ContentControl).
推荐答案
x:Type
位应该在花括号 {}
之间:
The x:Type
bit should be between curly braces {}
:
<DataTemplate DataType="{x:Type vm:TypeAViewModel}">
这篇关于如何基于ContentControl当前内容的数据类型自动使用DataTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!