I have an architect question:
I want to use Tree View to display some categories and on each categories if user clicks, need to show total product for that category.
What approach do I need to take?
Currently, I am trying to do:
1) Get Data from Database and load it to DataTable and DataTable is accessable from xaml.
2) Calling DataTable from xaml and binding TreeViewItem from dataTable Column…i.e.,
<TreeView ItemsSource="{Binding ElementName=_this, Path=SubCategoriesTable}" Name="trSubCategories">
<TreeView.ItemTemplate>
<DataTemplate>
<TreeViewItem Header="Home">
<TreeViewItem Header="{Binding Path=sub_category_name}"></TreeViewItem>
</TreeViewItem>
</DataTemplate>
</TreeView.ItemTemplate>
I don’t know is it a right approach to go? Or Should I add TreeViewItem in my code behind by looping though each datatable row and column?
Please help!
Use a HierarchicalDataTemplate and bind your
TreeViewaccordingly. You can use any object type as the backing for the binding; it doesn’t need to be aDataTable.You should avoid building out
TreeViewItem‘s in your code behind. It is simply not needed and makes down stream management more cumbersome then it needs to be.As noted by ChristopherS; Josh Smith has an excellent article on a TreeView with MVVM. Bea Stoliz also has a nice post on displaying grouped data in a TreeView.