Skip to main content

Bind to Hierarchical Data Structure

  • 11 minutes to read

A hierarchical data structure is a set of nested objects where a children field contains child records. Parents and children can be of different object types.

The DataControlBase.ItemsSource property contains only data items that correspond to root nodes. Use the following techniques to make the TreeListView work with the hierarchical data structure:

Child Nodes Path

View Example: Implement the Child Nodes Path

Use the Child Nodes Path to bind the TreeListView to a collection if all objects have the same children field. An example of such a structure is shown below:

public class BaseObject {
    public string Name { get; set; }
    public String Executor { get; set; }
    public ObservableCollection<Task> Tasks { get; set; }
}

public class ProjectObject : BaseObject {}

public class Task : BaseObject {
    public string State { get; set; }
}
  1. Set the TreeListView.ChildNodesPath property to the children field name.
  2. Set the TreeListView.TreeDerivationMode property to ChildNodesSelector.

    In the code sample below, the Tasks field is the children field:

    <dxg:TreeListControl Name="treeListView1" ItemsSource="{Binding DataItems}">
        <dxg:TreeListControl.Columns>
            <dxg:TreeListColumn FieldName="Name" AllowSorting="True" />
            <dxg:TreeListColumn FieldName="Executor" AllowSorting="True" />
            <dxg:TreeListColumn FieldName="State" AllowSorting="True" />
        </dxg:TreeListControl.Columns>
        <dxg:TreeListControl.View>
            <dxg:TreeListView TreeDerivationMode="ChildNodesSelector" ChildNodesPath="Tasks"/>
        </dxg:TreeListControl.View> 
    </dxg:TreeListControl>
    

Set the TreeListView.AllowChildNodeSourceUpdates property to true to update child nodes when you set the collection property to a new value.

Child Nodes Selector

Run Demo: Child Nodes Selector View Example: Use the Child Nodes Selector to Display Hierarchical Data

Use the Child Nodes Selector to create a hierarchical data structure in the TreeListView. An example of this structure is shown below:

public class ProjectObject : BaseObject {
    public ObservableCollection<ProjectStage> Stages { get; set; }
}

public class ProjectStage : BaseObject {
    public ObservableCollection<Task> Tasks { get; set; }
}

public class Task : BaseObject {
    State state;
    // ...
}
  1. Create a selector class that implements IChildNodesSelector, and override the SelectChildren(Object) method that returns node children.

    For the Project-Stage-Task class structure, the selector class is as follows:

    public class CustomChildrenSelector : IChildNodesSelector {
        public IEnumerable SelectChildren(object item) {
            if (item is ProjectStage)
                return ((ProjectStage)item).Tasks;
            else if (item is ProjectObject)
                return ((ProjectObject)item).Stages;
            return null;
        }
    }
    
  2. Assign the Child Nodes Selector to the TreeListView.ChildNodesSelector property.

  3. Set the TreeListView.TreeDerivationMode property to ChildNodesSelector.

    <dxg:TreeListControl ...>
        <dxg:TreeListControl.Resources>
            <local:CustomChildrenSelector x:Key="childrenSelector"/>
        </dxg:TreeListControl.Resources>
        <dxg:TreeListControl.View>
            <dxg:TreeListView TreeDerivationMode="ChildNodesSelector"
                              ChildNodesSelector="{StaticResource childrenSelector}"/>
        </dxg:TreeListControl.View>
    </dxg:TreeListControl>
    

Tip

If all objects have the same children field, assign its name to the TreeListView.ChildNodesPath property. Otherwise, create a Child Nodes Selector.

Fetch Nodes Asynchronously

Run Demo: Asynchronous Data Loading View Example: Load Nodes Asynchronously Without Locking the Application's UI

If your Child Nodes Selector returns a large number of nodes, the fetch operation could freeze the application. To avoid this, create an Asynchronous Child Nodes Selector and fetch child nodes in a background thread. During fetch operations, parent nodes display loading indicators and the TreeListView remains responsive to user actions.

TreeListView - Async Loading

  1. Create a selector that implements the IAsyncChildNodesSelector interface and override the HasChildNode and SelectChildrenAsync methods:

    public class CustomChildrenSelector : IAsyncChildNodesSelector {
        public Task<bool> HasChildNode(object item, CancellationToken token) {
            return Task.Run(async () => {
                await Task.Delay(250);
                return !(item is StageTask);
            });
        }
        public IEnumerable SelectChildren(object item) {
            throw new NotImplementedException();
        }
        public Task<IEnumerable> SelectChildrenAsync(object item, CancellationToken token) {
            return Task.Run(async () => {
                await Task.Delay(1000);
                return SelectChildNodes(item);
            });
        }
        public IEnumerable SelectChildNodes(object item) {
            if (item is ProjectStage)
                return (item as ProjectStage).StageTasks;
            else if (item is ProjectObject)
                return (item as ProjectObject).ProjectStages;
            return null;
        }
    }
    
  2. Assign the Child Nodes Selector to the TreeListView.ChildNodesSelector property.

  3. Set the TreeListView.TreeDerivationMode property to ChildNodesSelector.

    <dxg:TreeListControl ...>
        <dxg:TreeListControl.Resources>
            <local:CustomChildrenSelector x:Key="childrenSelector"/>
        </dxg:TreeListControl.Resources>
        <dxg:TreeListControl.View>
            <dxg:TreeListView TreeDerivationMode="ChildNodesSelector"
                              ChildNodesSelector="{StaticResource childrenSelector}"/>
        </dxg:TreeListControl.View>
    </dxg:TreeListControl>
    

The asynchronous child nodes selector does not fetch nodes if the TreeListView.EnableDynamicLoading property is set to false.

Hierarchical Data Templates

Run Demo: Hierarchical Data Templates View Example: Use Hierarchical Data Templates to Build a Tree

You can use templates to create a hierarchical data structure in the TreeListView. An example of this structure is shown below:

public class ProjectObject : BaseObject {
    public ObservableCollection<ProjectStage> Stages { get; set; }
}

public class ProjectStage : BaseObject {
    public ObservableCollection<Task> Tasks { get; set; }
}

public class Task : BaseObject {
    State state;
    // ...
}

If all objects have the same children field, create a hierarchical data template and assign it to the TreeListView.DataRowTemplate property. You can put hierarchical data templates into resources. Specify the data type to which a template should be applied:

<ResourceDictionary>
    <HierarchicalDataTemplate DataType="{x:Type local:ProjectObject}" ItemsSource="{Binding Path=Stages}" />
    <HierarchicalDataTemplate DataType="{x:Type local:ProjectStage}" ItemsSource="{Binding Path=Tasks}" />
</ResourceDictionary>

<dxg:TreeListControl.View>
    <dxg:TreeListView TreeDerivationMode="HierarchicalDataTemplate" />
</dxg:TreeListControl.View>

If all objects have different children fields:

  1. Create a template selector that implements the System.Windows.Controls.DataTemplateSelector and overrides the SelectTemplate method.

    <Window.Resources>
        <ResourceDictionary>
            <local:CustomHierarchicalDataTemplateSelector x:Key="selector">
                <local:CustomHierarchicalDataTemplateSelector.ProjectDataTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding Path=Stages}" />
                </local:CustomHierarchicalDataTemplateSelector.ProjectDataTemplate>
                <local:CustomHierarchicalDataTemplateSelector.ProjectStageDataTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding Path=Tasks}" />
                </local:CustomHierarchicalDataTemplateSelector.ProjectStageDataTemplate>
            </local:CustomHierarchicalDataTemplateSelector>
        </ResourceDictionary>
    </Window.Resources>
    
    public class CustomHierarchicalDataTemplateSelector : DataTemplateSelector {
    
        public HierarchicalDataTemplate ProjectDataTemplate { get; set; }
        public HierarchicalDataTemplate ProjectStageDataTemplate { get; set; }
    
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container) {
            var rowData = item as TreeListRowData;
            var element = rowData.Row;
            if (element is ProjectObject)
                return ProjectDataTemplate;
            if (element is ProjectStage)
                return ProjectStageDataTemplate;
            return null;
        }
    }
    
  2. Assign the template selector to the TreeListView.DataRowTemplateSelector property.

  3. Set the TreeListView.TreeDerivationMode property to HierarchicalDataTemplate.

    <dxg:TreeListControl.View>
        <dxg:TreeListView DataRowTemplateSelector="{StaticResource selector}"
                          TreeDerivationMode="HierarchicalDataTemplate" />
    </dxg:TreeListControl.View>
    

Note

Sort and Filter in Hierarchical Binding Mode

When the TreeListView is in hierarchical binding mode, users can sort and filter values if object types are the same. Set the TreeListView.AutoDetectColumnTypeInHierarchicalMode property to true to allow sorting/filtering (enabled by default).

Control whether to Create Child Nodes

You can control whether to create child nodes for a node. The following example shows how to prevent the TreeListView from creating child nodes for the Information Gathering node:

View Example: Control whether to Create Child Nodes

  1. In a data source, create a field that determines whether a node has children (the HasChildNodes field in the code sample below):

    public class BaseObject {
        public string Name { get; set; }
        public string Executor { get; set; }
        public ObservableCollection<Task> Tasks { get; set; }
        public bool HasChildNodes { get; set; }
    }
    
    public class ProjectObject : BaseObject { }
    
    public class Task : BaseObject {
        public string State { get; set; }
    }
    
    public class ViewModel {
        ObservableCollection<ProjectObject> InitData() {
            ObservableCollection<ProjectObject> projects = new ObservableCollection<ProjectObject>();
    
            ProjectObject betaronProject = new ProjectObject() { Name = "Project: Betaron", Executor = "Mcfadyen Ball", Tasks = new ObservableCollection<Task>(), HasChildNodes = true };
    
            Task Task11 = new Task() { Name = "Information Gathering", Executor = "Kaiden Savastano", Tasks = new ObservableCollection<Task>(), HasChildNodes = false };
            Task11.Tasks.Add(new Task() { Name = "Market research", Executor = "Carmine Then", State = "Completed", HasChildNodes = false });
            Task11.Tasks.Add(new Task() { Name = "Making specification", Executor = "Seto Kober", State = "In progress", HasChildNodes = false });
    
            Task Task12 = new Task() { Name = "Planning", Executor = "Manley Difrancesco", Tasks = new ObservableCollection<Task>(), HasChildNodes = true };
            Task12.Tasks.Add(new Task() { Name = "Documentation", Executor = "Martez Gollin", State = "Not started", HasChildNodes = true });
    
            // ...    
    
            ProjectObject stantoneProject = new ProjectObject() { Name = "Project: Stanton", Executor = "Ruben Ackerman", Tasks = new ObservableCollection<Task>(), HasChildNodes = true };
    
            Task Task21 = new Task() { Name = "Information Gathering", Executor = "Huyen Trinklein", Tasks = new ObservableCollection<Task>(), HasChildNodes = false };
            Task21.Tasks.Add(new Task() { Name = "Market research", Executor = "Tanner Crittendon", State = "Completed", HasChildNodes = false });
            Task21.Tasks.Add(new Task() { Name = "Making specification", Executor = "Carmine Then", State = "Completed", HasChildNodes = false });
    
            Task Task22 = new Task() { Name = "Planning", Executor = "Alfredo Sookoo", Tasks = new ObservableCollection<Task>(), HasChildNodes = true };
            Task22.Tasks.Add(new Task() { Name = "Documentation", Executor = "Gorf Wobbe", State = "Completed", HasChildNodes = true });
    
            // ...
        }
    } 
    
  2. Set the TreeListView.HasChildNodesPath property to this field’s name.

    <dxg:GridControl Name="treeListView1" ItemsSource="{Binding DataItems}">
        <dxg:GridControl.Columns>
            <dxg:GridColumn FieldName="Name"/>
            <dxg:GridColumn FieldName="Executor"/>
            <dxg:GridColumn FieldName="State"/>
        </dxg:GridControl.Columns>
        <dxg:GridControl.View>
            <dxg:TreeListView TreeDerivationMode="ChildNodesSelector" ChildNodesPath="Tasks" HasChildNodesPath="HasChildNodes"/>
        </dxg:GridControl.View>
    </dxg:GridControl>