本文介绍了WPF 使用 DataTemplate 隐式选择模板,但在“列表"之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有 TreeView,它包含各种类型的对象树(所有子类都来自同一个超类).

In my project, I have TreeView, which contains a tree of objects of various types (all subclassed from the same superclass).

在我的 TreeView 的右侧,我想要一个面板"(目前我只有一个网格),它显示有关当前在树中选择的对象的信息.我想使用 DataTemplate,如 此页面 上的第二个示例,以适应布局&我的面板"的内容基于子类类型;但是,我找不到合适的容器(因为我不需要列表控件 - 我想根据树视图中的选择更改一个项目的显示).

To the right of my TreeView I would like to have a "panel" (at the moment I just have a Grid) which displays information about the object currently selected in the tree. I want to use DataTemplate, as in the second example on this page, to adapt the layout & content of my "panel" based on the subclass type; however, I cannot find a suitable container (as I don't want a list control - I want to change my display for one item based on the selection in the treeview).

这个问题问了同样的问题,但我认为答案不适合因为我希望模板根据类型动态更改.

This question asks the same thing but I don't think the answer is suitable for me because I want the template to change dynamically depending on the type.

即我希望有类似的东西:

I.e. I was hoping for something like:

<[A Suitable Container] Margin="189,39,12,12" DataContext="{Binding ElementName=treeView1, Path=SelectedItem}">
<DataTemplate DataType="{x:Type local:subclass1}">
    <Grid>
        <!-- subclass1 specific stuff -->
    </Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type local:subclass2}">
    <Grid>
        <!-- subclass2 specific stuff -->
    </Grid>
</DataTemplate>
</[A Suitable Container]>

推荐答案

使用 ContentControl

<ContentControl Content="{Binding ElementName=treeView1, Path=SelectedItem}">
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type local:ViewModelA}">
            <local:ViewA />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ViewModelB}">
            <local:ViewB />
        </DataTemplate>
    </ContentControl.Resources>
</ContentControl>

这篇关于WPF 使用 DataTemplate 隐式选择模板,但在“列表"之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:50