New to Telerik UI for Blazor? Download free 30-day trial

Treeview Data Binding to Hierarchical Data

This article explains how to bind the TreeView for Blazor to hierarchical data. Before continuing, make sure you are familiar with the treeview data binding basics.

Hierarchical data means that the collection child items is provided in a field of its parent's model. By default, this is the Items field. If there are items for a certain node, it will have an expand icon. The HasChildren field can override this, however, but it is not required for hierarchical data binding.

This approach of providing nodes lets you gather separate collections of data and/or use different models at each different level. Note that the data binding settings are per level, so a certain level will always use the same bindings, regardless of the model they represent and their parent.

Example of hierarchical data that uses different models for the parent and the child. Using different models is not required.

Hierarchical data hold collections of the child items

<TelerikTreeView Data="@HierarchicalData" @bind-ExpandedItems="@ExpandedItems">
    <TreeViewBindings>
        <TreeViewBinding TextField="Category" ItemsField="Products" />
        <TreeViewBinding Level="1" TextField="ProductName" />
    </TreeViewBindings>
</TelerikTreeView>

@code {
    public IEnumerable<ProductCategoryItem> HierarchicalData { get; set; }
    public IEnumerable<object> ExpandedItems { get; set; } = new List<object>();

    public class ProductCategoryItem
    {
        public string Category { get; set; }
        public List<ProductItem> Products { get; set; }
    }

    public class ProductItem
    {
        public string ProductName { get; set; }
    }


    protected override void OnInitialized()
    {
        LoadHierarchical();
        ExpandedItems = HierarchicalData.Where(x => x.Products != null && x.Products.Any()).ToList();
    }

    private void LoadHierarchical()
    {
        List<ProductCategoryItem> roots = new List<ProductCategoryItem>();

        List<ProductItem> firstCategoryProducts = new List<ProductItem>()
    {
            new ProductItem { ProductName= "Category 1 - Product 1" },
            new ProductItem { ProductName= "Category 1 - Product 2" }
        };

        roots.Add(new ProductCategoryItem
        {
            Category = "Category 1",
            Products = firstCategoryProducts // this is how child items are provided

        });

        roots.Add(new ProductCategoryItem
        {
            Category = "Category 2" // we will set no other properties and it will not have children, nor will it be expanded
        });

        HierarchicalData = roots;
    }
}

See Also

In this article
Not finding the help you need? Improve this article