WPF Implicit selection of template using DataTemplate, but outside of 'List'

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 05:24:18

问题


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

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]>

回答1:


Use a 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>


来源:https://stackoverflow.com/questions/7175916/wpf-implicit-selection-of-template-using-datatemplate-but-outside-of-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!