Data Binding in WPF TreeGrid (SfTreeGrid)

12 Apr 202417 minutes to read

SfTreeGrid is designed to display the self-relational and hierarchical data in tree structure with columns. The data binding can be achieved by assigning the data source to SfTreeGrid.ItemsSource property directly through self-relational binding or nested collection or retrieving the parent and child nodes items dynamically using RequestTreeItems or LoadOnDemandCommand.
If the data source implements INotifyCollectionChanged interface, then SfTreeGrid control will automatically refresh the UI when item is added, removed or while list cleared. When you add, remove item inObservableCollection, SfTreeGrid automatically refresh the UI as ObservableCollection’ implements INotifyCollectionChanged. But when you do the same in List, SfTreeGrid will not refresh the UI automatically.

Below are the ways to bind the data source to SfTreeGrid.

Binding with IEnumerable

SfTreeGrid control supports to bind any collection that implements the IEnumerable interface. Data operations such as sorting is supported when you are binding collection derived from IEnumerable.

Binding with dynamic data object

SfTreeGrid control supports to bind dynamic data object. Below are the limitations when you are binding dynamic data object,

  1. In UWP, UI won’t get refreshed when you are changing the property value. This is limitation in UWP platform.
  2. SfTreeGrid doesn’t support LiveNodeUpdateMode - AllowDataShaping.

Binding Complex properties

SfTreeGrid control provides support to bind complex property to its columns. To bind the complex property to TreeGridColumn, set the complex property path to MappingName.

<syncfusion:SfTreeGrid x:Name="treeGrid"
                       ChildPropertyName="Children"
                       ItemsSource="{Binding PersonDetails}"
                       ShowRowHeader="True">
            <syncfusion:SfTreeGrid.Columns>
                <syncfusion:TreeGridColumns>
                    <syncfusion:TreeGridTextColumn MappingName="FirstName" />
                    <syncfusion:TreeGridTextColumn MappingName="Address.City" />
                    <syncfusion:TreeGridTextColumn MappingName="Address.Country" />
                </syncfusion:TreeGridColumns>
            </syncfusion:SfTreeGrid.Columns>
 </syncfusion:SfTreeGrid>

Limitations when binding complex property:

SfTreeGrid doesn’t support LiveNodeUpdateMode - AllowDataShaping.

Binding Indexer properties

SfTreeGrid control provides support to bind an indexer property to its columns. To bind an indexer property to TreeGridColumn, set the indexer property path to MappingName.

<syncfusion:SfTreeGrid x:Name="treeGrid"
                       AutoGenerateColumns="False"
                       ItemsSource="{Binding Students}">
            <syncfusion:SfTreeGrid.Columns>
                <syncfusion:TreeGridTextColumn MappingName="RollNo" />
                <syncfusion:TreeGridTextColumn MappingName="Name" />
                <syncfusion:TreeGridTextColumn MappingName="Marks[0]" />
            </syncfusion:SfTreeGrid.Columns>
</syncfusion:SfTreeGrid>
this.treeGrid.Columns.Add(new TreeGridTextColumn() {MappingName="Marks[0]"});

Limitations when binding complex property:

SfTreeGrid doesn’t support LiveNodeUpdateMode - AllowDataShaping.

AutoExpandMode

By setting SfTreeGrid.AutoExpandMode property, you can let the SfTreeGrid to expand the nodes while loading.

Mode

Description

AllNodesExpanded All the nodes will be expanded while at the time of loading.
None None defines the node is not expanded when loading. By default, root nodes only will be displayed.
RootNodeExpanded Root nodes only will be expanded at the time of loading.
<syncfusion:SfTreeGrid Name="treeGrid"
                       AutoExpandMode="AllNodesExpanded"
                       AutoGenerateColumns="False"
                       ChildPropertyName="ReportsTo"
                       ItemsSource="{Binding Employees}"
                       ParentPropertyName="ID"/>
treeGrid.AutoExpandMode = AutoExpandMode.AllNodesExpanded;

Expanding a tree node

You can expand a node based on its level or row index. Here is a list of ways to expand a node,

Method

Description

ExpandAllNodes()

Expands all the nodes including its inner leaf nodes

ExpandAllNodes(int level)

Expand all the nodes up to the specified level

ExpandAllNodes(TreeNode treeNode)

Expand the specific node and its child nodes

ExpandNode(int rowIndex)

Expand a node at the specific row Index

ExpandNode(TreeNode treeNode)

Expands the specific node.

Expand all the nodes

You can expand all the nodes programmatically at runtime by using SfTreeGrid.ExpandAllNodes method.

treeGrid.ExpandAllNodes();

Expand the nodes based on its level

You can expand the nodes based on the level by using SfTreeGrid.ExpandAllNodes method by passing level as argument.

treeGrid.ExpandAllNodes(1);

Expand the specific node

You can expand the specific node by using SfTreeGrid.ExpandNode method.

var node = treeGrid.View.Nodes[0];
treeGrid.ExpandNode(node);

You can expand the node at specific index also by using SfTreeGrid.ExpandNode method.

treeGrid.ExpandNode(2);

Expand the specific node based on business object

You can expand the node corresponding to specific data object by resolving node and calling SfTreeGrid.ExpandNode method.

var data = (this.DataContext as ViewModel).PersonDetails[0];
var node = this.treeGrid.View.Nodes.GetNode(data);
treeGrid.ExpandNode(node);

Expand all the nodes

You can expand the specific node and all its child nodes by using SfTreeGrid.ExpandAllNodes methods.

var node = treeGrid.View.Nodes[0];
treeGrid.ExpandAllNodes(node);

Cancel the node Expanding using NodeExpanding event

You can cancel the node expanding through SfTreeGrid.NodeExpanding event.

treeGrid.NodeExpanding += TreeGrid_NodeExpanding;

private void TreeGrid_NodeExpanding(object sender, NodeExpandingEventArgs e)
{
    e.Cancel = true;    
}

You can cancel the specific node being expanded by using SfTreeGrid.NodeExpanding event and Node property,

treeGrid.NodeExpanding += TreeGrid_NodeExpanding;

private void TreeGrid_NodeExpanding(object sender, NodeExpandingEventArgs e)
{

    if ((e.Node.Item as EmployeeInfo).ID == 2)
        e.Cancel = true;
}

NodeExpanded Event

You can get the notification once a node is expanded from TreeGrid.NodeExpanded event and here you can get the expanded node and its child nodes.

private void TreeGrid_NodeExpanded(object sender, NodeExpandedEventArgs e)
{
    var node = e.Node;
    var childNodes = e.Node.ChildNodes;
}

Collapsing a tree node

You can collapse all the tree nodes or specific node and its child nodes. Here is a list of ways to collapse a node,

Method

Description

CollapseAllNodes()

Collapse all the nodes in SfTreeGrid

CollapseAllNodes(TreeNode treeNode)

Collapse the specific node and its child nodes

CollapseNode(int rowIndex)

Collapse the node at specific row index

CollapseNode(TreeNode treeNode)

Collapse the specific node in SfTreeGrid

Collapse all the nodes

You can collapse all the nodes programmatically at runtime by using SfTreeGrid.CollapseAllNodes methods

treeGrid.CollapseAllNodes();

Collapse the specific node

You can collapse the specific node by using SfTreeGrid.CollapseNode method.

var node = treeGrid.View.Nodes[0];
treeGrid.CollapseNode(node);

You can collapse the node at specific index also by using SfTreeGrid.CollapseNode method.

treeGrid.CollapseNode(2);

Collapse the specific node based on business object

You can collapse the node corresponding to specific data object by resolving node and calling SfTreeGrid.CollapseNode method.

var data = (this.DataContext as ViewModel).PersonDetails[0];
var node = this.treeGrid.View.Nodes.GetNode(data);
treeGrid.CollapseNode(node);

Collapse all the nodes

You can collapse the specific node and all its child nodes by using SfTreeGrid.CollapseAllNodes methods.

var node = treeGrid.View.Nodes[0];
treeGrid.CollapseAllNodes(node);

Cancel the node collapsing using NodeCollapsing Event

You can cancel the node collapsing operation through TreeGrid.NodeCollapsing event.

treeGrid.NodeCollapsing += TreeGrid_NodeCollapsing;

private void TreeGrid_NodeCollapsing(object sender, NodeCollapsingEventArgs e)
{
    e.Cancel = true;
}

You can cancel the specific node being collapsed by using TreeGrid.NodeCollapsing event.

treeGrid.NodeCollapsing += TreeGrid_NodeCollapsing;

private void TreeGrid_NodeCollapsing(object sender, NodeCollapsingEventArgs e)
{

    if ((e.Node.Item as EmployeeInfo).ID == 2)
        e.Cancel = true;
}

NodeCollapsed Event

You can get the notification once a node is collapsed from TreeGrid.NodeCollapsed event and here you can get the collapsed node.

treeGrid.NodeCollapsed += TreeGrid_NodeCollapsed;

private void TreeGrid_NodeCollapsed(object sender, NodeCollapsedEventArgs e)
{
    var node = e.Node;
}

Expand/Collapse a node based on mapping property

SfTreeGrid supports to expand/collapse the nodes based on the value of a boolean mapping property in the underlying data object by using SfTreeGrid.ExpandStateMappingName property. TreeGrid expand/collapse the node when the specified property value in underlying data object gets changed.

<syncfusion:SfTreeGrid Name="treeGrid"
                       ExpandStateMappingName="IsExpanded"
                       ChildPropertyName="Children"
                       ItemsSource="{Binding PersonDetails}"
                       ShowCheckBox="True"/>
treeGrid.ExpandStateMappingName = "IsExpanded";

LiveNodeUpdateMode

SfTreeGrid listens and responds to the manipulation such as add, delete and data update (property change) at runtime. SfTreeGrid refreshes the sorting based on SfTreeGrid.LiveNodeUpdateMode property. If you set LiveNodeUpdateMode as AllowDataShaping, sorting will be refreshed on data manipulation and property change.

<syncfusion:SfTreeGrid  Name="treeGrid"
                        AllowEditing="True"
                        AutoExpandMode="RootNodesExpanded"
                        LiveNodeUpdateMode="AllowDataShaping"
                        AutoGenerateColumns="False"
                        ChildPropertyName="ReportsTo"
                        ItemsSource="{Binding Employees}"
                        ParentPropertyName="ID"/>
treeGrid.LiveNodeUpdateMode = LiveNodeUpdateMode.AllowDataShaping;

Events

ItemsSourceChanged

SfTreeGrid.ItemsSourceChanged event occurs when the data source is changed by using ItemsSource property.

This event receives two arguments namely sender that handles SfTreeGrid and GridItemsSourceChangedEventArgs as objects.
The GridItemsSourceChangedEventArgs object contains the following properties:

  • OldItemsSource - Gets the value of old data source
  • NewItemsSource - Get the value of new data source

View

SfTreeGrid has the View property of type TreeGridView. View is responsible for maintaining and manipulating the nodes and other advanced operations like Sorting. When you bind Collection to ItemsSource property of SfTreeGrid or wire RequestTreeItems event, then View will be created and maintains the operations on nodes.

SfTreeGrid creates different types of views derived from TreeGridView based on data population methods.

TreeGridSelfRelationalView - While populating data using self-relational binding

TreeGridNestedView - While populating data using nested collection

TreeGridUnboundView - While populating data with RequestTreeItems event or LoadOnDemandCommand command

Events

The following events are associated with View.

RecordPropertyChanged

This event is raised when the DataModel property value is changed, if the DataModel implements the INotifyPropertyChanged interface. The event receives with two arguments namely sender that handles the DataModel and PropertyChangedEventArgs as object.

PropertyChangedEventArgs has below property,

PropertyName – It denotes the PropertyName of the changed value.

NodeCollectionChanged

This event is raised whenever there is some change in nodes collection. The event receives two arguments namely sender that handles View object and NotifyCollectionChangedEventArgs as object.
NotifyCollectionChangedEventArgs has below properties,

  • Action - It contains the current action. (i.e.) Add, Remove, Move, Replace, Reset.
  • NewItems - It contains the list of new items involved in the change.
  • OldItems - It contains the list of old items affected by the Action.
  • NewStartingIndex - It contains the index at which the change occurred.
  • OldStartingIndex - It contains the index at which the Action occurred.

SourceCollectionChanged

This event is raised when you make changes in SourceCollection for example add or remove the collection. The event receives two arguments namely sender that handles that handles View object and NotifyCollectionChangedEventArgs as object.
NotifyCollectionChangedEventArgs has below properties,

  • Action - It contains the current action. (i.e) Add, Remove, Move, Replace, Reset.
  • NewItems - It contains the list of new items involved in the change.
  • OldItems - It contains the list of old items affected by the Action.
  • NewStartingIndex - It contains the index at which the change occurred.
  • OldStartingIndex- It contains the index at which the Action occurred.

Methods

The following are the methods that are associated with View which can be used to defer refresh the view.

DeferRefresh

Enter the defer cycle so that you can perform all data operations in view and update once. You can refresh the nodes or completely recreates the nodes by using TreeViewRefreshMode parameter.

using (treeGrid.View.DeferRefresh(TreeViewRefreshMode.NodeRefresh))
{
    treeGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "FirstName", SortDirection = ListSortDirection.Descending });
    treeGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "Id", SortDirection = ListSortDirection.Descending });
}

BeginInit and EndInit

When <code>BeginInit</code> method is called, it suspends all the updates until <code>EndInit</code> method is called. You can perform all the update with in these methods and update the view at once. You can refresh the nodes or completely recreates the nodes by using TreeViewRefreshMode parameter.

treeGrid.View.BeginInit(TreeViewRefreshMode.DeferRefresh);
treeGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "FirstName", SortDirection = ListSortDirection.Descending });
treeGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "Id", SortDirection = ListSortDirection.Descending });
treeGrid.View.EndInit();

NOTE

View has properties (EnableRecursiveChecking, LiveNodeUpdateMode , RecursiveCheckingMode,..)that already defined in SfTreeGrid. It is recommended to set those properties via SfTreeGrid.

NOTE

You can refer to our WPF TreeGrid feature tour page for its groundbreaking feature representations. You can also explore our WPF TreeGrid example to know how to render and configure the treegrid.