Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...