开发者

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 ?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜