usergaro
usergaro

Reputation: 427

What approach should I take to Bind data to TreeView?

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!

Upvotes: 1

Views: 250

Answers (2)

Aaron McIver
Aaron McIver

Reputation: 24713

Use a HierarchicalDataTemplate and bind your TreeView accordingly. You can use any object type as the backing for the binding; it doesn't need to be a DataTable.

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.

Upvotes: 1

ChristopherS
ChristopherS

Reputation: 883

This is probably by far the best tutorial you can find about this topic: http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx

Upvotes: 0

Related Questions