Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
946 views
in Technique[技术] by (71.8m points)

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

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]>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...