Self-Referencing collection in TreeView WPF

PUBLISHED ON 8 FEB 2019 — WPF

Sometimes we have a self-referencing collection which we want to display to the user in form for a treeview.

Suppose we have a class Manager which has a collection of “derived” managers and each of this managers is also in charge of another managers.

Our class could look like this

public class Manager
{
    public int Id {get;set;}
    public int Name {get;set;}
    public int SourceManagerId {get;set;}

    public Manager SourceManager{get;set;}
    public ICollection DerivedManagers {get;set;}
}

WPF has built-in support for this situation with the HierarchicalDataTemplate.

Here is a basic example of using a HierarchicalDataTemplate in a TreeView.

Here our view XAML:

<TreeView Name="TreeView" Grid.Row="0"
          FontSize="11" FontWeight="Normal"
          ItemsSource={Binding RootManagers}>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Childs}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Id}" />
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

Code-Behind:

public partial class MyWindow:Window
{
    ...
    public BindingList<Manager> RootManagers {get;set;}
    ...
}

To get our RootManagers we can just call

RootManagers = ManagerCollection.Where(m => m.SourceManagerId == 0)

which will give us all managers without a SourceManager.

comments powered by Disqus