saloni
saloni

Reputation: 51

Multi level Nested TreeView with Dynamic Binding in WPF

I am trying to create an application in which i require to display employees and their departments in the treeview kind of structure as below :

how could i do this with WPF ?

Upvotes: 5

Views: 7179

Answers (2)

user6283344
user6283344

Reputation:

If you've structure like this:

public ObservableCollection<ChartOfAccount> ChartOfAccounts { get; set; }

public class ChartOfAccount
{
    public Book Book { get; set; }
    public List<LedgerHierarchy> ControlLedgers { get; set; }
}

public class LedgerHierarchy
{
    public ControlLedger ControlLedger { get; set; }
    public ObservableCollection<Ledger> Ledgers { get; set; }
}

you could bind directly in TreeView like this:

<TreeView ItemsSource="{Binding ChartOfAccounts}"
          BorderThickness="0"
          ScrollViewer.HorizontalScrollBarVisibility="Disabled"
          ItemContainerStyle="{StaticResource treeStyle}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding ControlLedgers}">
            <TextBlock Text="{Binding Book.Name}"/>
            <HierarchicalDataTemplate.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Ledgers}">
                    <TextBlock Text="{Binding ControlLedger.Name}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Name}"/>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

instead of creating HierarchicalDataTemplate in Control.Resource.

Upvotes: 0

Vogel612
Vogel612

Reputation: 5647

The correct way to do this is to use a HierarchicalDataTemplate. The most basic one I can imagine is the following:

<UserControl.Resources>
        <HierarchicalDataTemplate
            x:Key="RecursiveData" DataType="TreeViewItem" ItemsSource="{Binding Items}">
        </HierarchicalDataTemplate>
    </UserControl.Resources>

Which can be used in the XAML as follows:

<TreeView ItemTemplate="{StaticResource RecursiveData}" />

Of course you can customize the template at will with styles and subcomponents.

Note that the ItemSource of your TreeView needs to actually provide nested TreeViewItems where each TreeViewItem contains it's subitems in Items.

Upvotes: 2

Related Questions