Directory Freebies VS CheatSheet Forum

RSS

Email

Translate

Home About Archive Privacy Contact Advertise Write for Dev102
Posted by Amit on Jan 5th, 2008 | Filed under .Net, C#, Visual Studio, WPF |

Hi all.

First of all Let me give credit to Shahar A. for showing me this.

As it turns out, my latest post about DataTemplates was not the most efficient way to do this.

I used a different Template for the root and a second one for the all the rest of the data.

What i learned is that it is possible to do this with just one template for all. So now i am going to show you the best way to use hierarchical DataTemplates. The change is a minor one.

at the first example we defined the TreeView in the following way:

<TreeView Margin="0,0,15,0" Name="treeView1" Background="LightSkyBlue"> 

  <TreeViewItem ItemsSource="{Binding}" Header="{Binding PageTitle}"/> 
  </TreeView>

 The implementation of the tree view should look like this:
<TreeView Margin="0,0,15,0" Name="treeView1" Background="LightSkyBlue"> 

  <TreeViewItem IsExpanded="True" ItemsSource="{Binding LinksInPage}"/> 
 </TreeView>

Notice the difference? look at the ItemsSource attribute at the TreeViewItem instead of just writing {Binding} we wrote {Binding LinksInPage} and apparently that made all the difference. Now we can get rid of the root DataModel and the root Template Wipee!!!if you want you can add a header attribute to make the root visible like this:

<TreeView Margin="0,0,15,0" Name="treeView1" Background="LightSkyBlue"> 

  <TreeViewItem IsExpanded="True" ItemsSource="{Binding LinksInPage}">  

  <TreeViewItem.Header> 

  <StackPanel>  

    <TextBlock Margin="10,0,10,0" Text="{Binding PageTitle}">
</TextBlock>   

<TexttBlock Margin="10,0,10,0" Text="{Binding Href}"></TextBlock> 
    </StackPanel>      
</TreeViewItem.Header>  </TreeViewItem> </TreeView>

Subscribe to our feed and get the complete code sample for this article

pre>
the old implementation is commented out so you can see the difference.
Enjoy.
Amit.
Tags: , , , , , , ,

2 Responses to “How to Use Hierarchical DataTemplates - Improved !!!”


  1. Matt Elphick Said on May 6, 2008 :

    Thank you so much, I’d spent all morning chasing this.

  2. Gaius Said on Dec 13, 2009 :

    How can I allso do grouping with CollectionViewSource? I Have groups and subgroups. All items belong into a group but SOME items belong allso into subgroup

Post a Comment

Write Article for Dev102

Write for Dev102!

We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution

Learn More