Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying UserControls based on the type a TreeView selection is bound to

Tags:

wpf

I am making an app in WPF in a style similar to Windows Explorer, with a TreeView on the left and a pane on the right.

I want the contents of the right pane to change depending on the type of the selected element in the TreeView.

For example, say the top level in the Tree View contains objects of class "A", and if you expand the "A" object you'll see a list of "B" objects as children of the "A" object.

If the "A" object is selected, I want the right pane to show a user control for "A", and if "B" is selected I want the right pane to show a user control for "B".

I've currently got this working by:

  • setting up the TreeView with one HierarchialDataTemplate per type
  • adding all the UserControls to the right pane, but collapsed
  • implementing SelectedItemChanged on the TreeView, and setting the appropriate usercontrol to visible and the others to collapsed.

    However, I'm sure there's a better/more elegant way to switch out the views based on the type the selection is bound to, perhaps by making more use of data binding... any ideas?

  • like image 339
    Ray Wenderlich Avatar asked Apr 08 '10 01:04

    Ray Wenderlich


    2 Answers

    Have you considered displaying a ContentControl as the right-side pane, and using DataTemplates to customize the contents? Then you could simply bind the right pane to the selected item of the TreeView.

    For example:

    <ContentControl Content="{Binding SelectedItem,ElementName=treeView1}">
        <ContentControl.Resources>
            <DataTemplate DataType="{x:Type my:A}">
                <StackPanel>
                    <TextBlock Text="Displaying an A!" />
                    <TextBlock Text="{Binding Foo}" />
                </StackPanel>
            </DataTemplate>
    
            <DataTemplate DataType="{x:Type my:B}">
                <StackPanel>
                    <TextBlock Text="Displaying a B!" />
                    <TextBlock Text="{Binding Bar}" />
                </StackPanel>
            </DataTemplate>
        </ContentControl.Resources>
    </ContentControl>
    
    like image 55
    Matt Hamilton Avatar answered Sep 18 '22 07:09

    Matt Hamilton


    You can use the ContentPresenter class with a DataTemplateSelector. Bind the Content property to the TreeView.SelectedItem property then use the DataTemplateSelector to conditionally choose the template.

    like image 31
    Josh Avatar answered Sep 21 '22 07:09

    Josh