views:

449

answers:

2

Hi

I have a tree view which has three levels.

Lets say its a league, division and team treeview.

Now, when I select each of the items in the tree, I would like to see detailed information about it.

Whats the best way to achieve this?

Since Grid doesn't items (like a ListBox), I can't just set its ItemsSource and make a DataTemplate...

I thought about using a ListBox which will contain only the selected item but this seems to be very bad...

Thanks.

A: 

I would create a viewmodel with properties for the tree structur, the current selection and the details to the current selection.

The tree struct is one-way bound to the treeview, the SelectedItem from the treeview is OneWayToSource bound to the current selection property (due to the limitations of the property). This property changes the list of child items once the current selection changes, and the child items are bound to the listbox displaying them.

Martin Moser
+1  A: 

You first define the 3 data template for your league, division and team classes. After, you bind the TreeView to the root of your objects. Your League and Division classes should have a Children property that returns the children. All your classes should have a Name property.

Then when you want to show a single object, use the ContentPresenter, and the bind its content to the SelectedItem if the TreeView.

For example:

<StackPanel>
   <StackPanel.Resources>

       <DataTemplate DataType="{x:Type your_namespace:League}">
           <StackPanel Orientation="Vertical">
               <TextBlock Text={Binding Name}/>
               <.../>
           <StackPanel>
       </DataTemplate>

       <DataTemplate DataType="{x:Type your_namespace:Division}">
           <StackPanel Orientation="Vertical">
               <TextBlock Text={Binding Name}/>
               <.../>
           <StackPanel>
       </DataTemplate>

       <DataTemplate DataType="{x:Type your_namespace:Team}">
           <StackPanel Orientation="Vertical">
               <TextBlock Text={Binding Name}/>
               <.../>
           <StackPanel>
       </DataTemplate>

   </StackPanel.Resources>

   <TreeView x:Name="_tree" ItemsSource="{Binding RootOfYourItems}">
      <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <TextBlock Text={Binding Name}/>
        </HierarchicalDataTemplate>
   </TreeView>

   <ContentPresenter Content="{Binding Path=SelectedItem, ElementName=_tree}" />

</StackPanel>

This code was not tested or compiled, it just provided as an example.

decasteljau
Thanks, I was unaware of the power of ContentPresenter, got it working :)
Tsury