如何根据 ContentControl 的当前内容的数据类型自动使用数据模板
当我尝试指定多个 DataTemplate 供 ContentControl 使用以便使用正确的 DataTemplate(基于类型)时,我最终得到的 Content 只是 Content 的 ToString() 值。
<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>
在上面的示例中,当 CurrentlySelectedTreeViewModel
返回 TypeAViewModel
的树节点时,我会看到 MyApp.ViewModel.TypeAViewModel
显示。我希望看到我的 TypeAViewModelUserControl
。
我尝试将单个
元素放入我的一个数据模板中,只是为了查看问题是否与我的用户控件有关。相同的结果。
有什么想法我做错了吗?
(顺便说一句,CurrentlySelectedTreeViewModel
是一个返回 TreeView
中当前选定节点的属性。它似乎工作得很好 - 当我在树中选择节点时,出现节点的正确类型名称 ContentControl
)。
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>
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
.
I've tried putting a single <TextBlock Text="TESTING"/>
element in one of my data templates just to see if the problem was related to my user controls. Same result.
Any ideas what I am doing wrong?
(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
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
x:Type
位应位于大括号{}
之间:The
x:Type
bit should be between curly braces{}
:x:Type
是一个 MarkupExtension,它需要{}
向 XAML 编译器指示。x:Type
is a MarkupExtension, which requires{}
to indicate to the XAML compiler.