Is there any simple tutorial for beginners about treeview binding in WPF?
What should we write in ItemsSource, DataType, ItemTemplate attributes if there's one List of items?
IList<string> items = new List<string>(); items.Add("item1"); items.Add("item2"); items.Add("item3");
XAML code:
<TreeView Name="treeView1"> <TreeView.Resources> <!-- what does it mean? --> <HierarchicalDataTemplate DataType="???" ItemsSource="{Binding ???}"></HierarchicalDataTemplate> </TreeView.Resources> </TreeView>
To Fully understand how to use the wpf treeview with data binding, I went through the following tutorials in order -
http://testdrivendevelopment.wordpress.com/2008/07/15/databinding-wpf-treeview-using-recursion/
http://blog.clauskonrad.net/2011/04/how-to-make-hierarchical-treeview.html
http://blogs.msdn.com/b/mikehillberg/archive/2009/10/30/treeview-and-hierarchicaldatatemplate-step-by-step.aspx
The trick is that ItemsSource
points to the next collection down.
e.g Imagine you have a collection of type A, and each A contains a description and a collection of type B; and each B contains a description and a collection of type C. The binding would look like this:
<TreeView Width="400" ItemsSource="{Binding CollectionOfA}"> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type TypeA}" ItemsSource="{Binding CollectionOfB}"> <TreeViewItem Header="{Binding TypeADescription}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type TypeB}" ItemsSource="{Binding CollectionOfC}"> <TreeViewItem Header="{Binding TypeBDescription" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type TypeC}"> <TreeViewItem Header="{Binding TypeC}" /> </HierarchicalDataTemplate> </TreeView.Resources> </TreeView>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With