DxTreeView Class

A TreeView component.

Namespace: DevExpress.Blazor

Assembly: DevExpress.Blazor.v21.2.dll

Declaration

public class DxTreeView :
    DxNavigationControlComponent<DxTreeView, TreeViewJSInteropProxy>,
    ITreeViewJSInteropProxyServer,
    IJSCallback,
    IModelWrapper<ITreeViewModel>

Remarks

The DevExpress TreeView component for Blazor (<DxTreeView>) displays hierarchical data structures within a tree-like UI. The component implements navigation within a web application.

Blazor Navigation Landing TreeView

Run Demo: TreeView

Add a TreeView to a Project

Follow the steps below to add the TreeView component to an application:

  1. Use a DevExpress Project Template to create a new Blazor Server or Blazor WebAssembly application. If you use a Microsoft project template or already have a Blazor project, configure your project to incorporate DevExpress Blazor components.
  2. Add the <DxTreeView></DxTreeView> markup to a Razor page.
  3. Configure the component: add nodes or bind the TreeView to data, handle expand/collapse events, enable node selection, and so on (see the sections below).

Nodes / Unbound Mode

The <DxTreeView> component supports bound and unbound modes. In unbound mode, the user should populate a node hierarchy. Root nodes are stored within the TreeView’s Nodes collection. Each node has its own collection of child nodes that you can access from its Nodes property.

A DxTreeViewNode class instance defines a node in code, and the Name property specifies its unique name. Use the Text property to specify the node’s text, the IconCssClass property to specify a CSS class for the node’s icon, and the NavigateUrl property to specify the URL to navigate to when the node is clicked.

TreeView Nodes

<DxTreeView>
  <Nodes>
    <DxTreeViewNode Name="Overview" Text="Overview" NavigateUrl="https://demos.devexpress.com/blazor/" />
    <DxTreeViewNode Name="Editors" Text="Data Editors" Expanded="true">
      <Nodes>
        <DxTreeViewNode Text="Combobox" NavigateUrl="https://demos.devexpress.com/blazor/ComboBox" />
        <DxTreeViewNode Text="Spin Edit" NavigateUrl="https://demos.devexpress.com/blazor/SpinEdit" />
      </Nodes>
    </DxTreeViewNode>
    <DxTreeViewNode Name="FormLayout" Text="Form Layout" NavigateUrl="https://demos.devexpress.com/blazor/FormLayout" BadgeText="Upd" />
    <DxTreeViewNode Name="TreeView" Text="TreeView" NavigateUrl="https://demos.devexpress.com/blazor/TreeView" BadgeText="New"  />
    <DxTreeViewNode Name="Tabs" Text="Tabs" NavigateUrl="https://demos.devexpress.com/blazor/Tabs" Visible="false" BadgeText="New" />
  </Nodes>
</DxTreeView>

Data Binding

The TreeView component supports binding to data. In the bound mode, items from the data source automatically populate TreeView nodes.

Follow the steps below to bind TreeView to data:

  1. Use the Data property to specify a data source. You can use different data types:

    • Flat data - a collection of items that are available at one level.
    • Hierarchical data - a collection of nested nodes.
  2. Add the DataMappings tag to the component’s markup.

  3. Create the DxTreeViewDataMapping instance and map node properties (HasChildren, IconCssClass, and so on) to data source fields. Mappings are used to link the TreeView data model to the data source.

    • Flat data - the Key and ParentKey properties are required. If the TreeView’s structure consists of only one level, you can omit these properties.

    • Hierarchical data - the Children property is required.

    You can also create multiple DxTreeViewDataMapping instances to specify different mappings for different node levels. Use the Level property to specify the node level for which data mappings are applied.

Flat Data

The code below binds the TreeView to the collection of flat data items. It specifies mappings for the Text, Key, and ParentKey properties.

@if(Data == null) {
    <p><em>Loading...</em></p>
}
else {
    <div class="cw-320">
        <DxTreeView Data="@Data">
            <DataMappings>
                <DxTreeViewDataMapping Text="Name"
                                       Key="Id"
                                       ParentKey="CategoryId" />
            </DataMappings>
        </DxTreeView>
    </div>
}

@code {
    List<FlatDataItem> Data { get; set; }

    protected override void OnInitialized() {
        IEnumerable<ProductFlat> products = ProductData.Products;
        IEnumerable<ProductCategory> productSubcategories = ProductData.Categories;

        Data = new List<FlatDataItem>(Enum.GetValues<ProductCategoryMain>().Select(i => new FlatDataItem() { Name = i.ToString(), Id = i }));
        Data.AddRange(products.Select(i => new FlatDataItem() { Name = i.ProductName, Id = i.Id, CategoryId = i.ProductCategoryId }));
        Data.AddRange(productSubcategories.Select(i => new FlatDataItem() { Name = i.Subcategory, Id = i.SubcategoryID, CategoryId = i.Category }));
    }
}

Bind Treview to Flat Data

Run Demo: TreeView - Binding to Flat Data

Hierarchical Data

The code below binds the TreeView to the collection of ChemicalElementGroup objects. Each object can have child objects. The code specifies the Children and Text mappings to adjust the TreeView data model to the specified data source.

<DxTreeView Data="@ChemicalElements.Groups">
    <DataMappings>
        <DxTreeViewDataMapping Children="Groups"
                               Text="Name"/>
    </DataMappings>
</DxTreeView>

Bind Treview to Hierarchical Data

Run Demo: TreeView - Binding to Hierarchical Data

Expand/Collapse Nodes

Users can click a node or its Expand/Collapse button to expand/collapse the node. When node selection is enabled, users should double-click nodes or click the Expand/Collapse buttons.

TreeView Expand Collapse Buttons

The table below lists related API members.

Member

Description

NodeExpandCollapseAction

Specifies user actions that expand or collapse a node.

ShowExpandButtons

Specifies whether expand buttons are visible.

SetNodeExpanded(Func<ITreeViewNodeInfo, Boolean>, Boolean)

Expands or collapses the specified node.

GetNodeExpanded(Func<ITreeViewNodeInfo, Boolean>)

Returns whether the specified node is expanded.

ExpandToNode(Func<ITreeViewNodeInfo, Boolean>)

Expands the nodes down to the specified node.

ExpandAll()

Expands all nodes in the DxTreeView.

CollapseAll()

Collapses all nodes in the DxTreeView.

ExpandButtonIconCssClass

Specify a CSS class for the expand button’s icon.

CollapseButtonIconCssClass

Specify a CSS class for the collapse button’s icon.

The following events fire when a node’s state changes:

Member

Description

BeforeExpand

Fires when a node is about to be expanded and allows you to cancel the action.

BeforeCollapse

Fires when a node is about to be collapsed and allows you to cancel the action.

AfterExpand

Fires after a node has been expanded.

AfterCollapse

Fires after a node has been collapsed.

Node Selection

Set the AllowSelectNodes property to true to enable node selection. Once a user clicks a node, it is highlighted and the SelectionChanged event is raised. The following example demonstrates how to handle this event to expand the selected node if it has children and collapse other nodes:

<DxTreeView @ref="@treeView" AllowSelectNodes="true" SelectionChanged="@SelectionChanged">
  ...
</DxTreeView>

@code  {
    DxTreeView treeView;

    protected void SelectionChanged(TreeViewNodeEventArgs e)  {
        treeView.CollapseAll();
        treeView.ExpandToNode((n) => n.Text == e.NodeInfo.Text);
        if (!e.NodeInfo.IsLeaf) {
          treeView.SetNodeExpanded((n) => n.Text == e.NodeInfo.Text, true);
        }    
    }
}

Run Demo: TreeView - Node Selection

The table below lists other related API:

Member

Description

GetSelectedNodeInfo()

Returns information about the selected node.

SelectNode(Func<ITreeViewNodeInfo, Boolean>)

Selects the specified node.

ClearSelection()

Clears node selection.

Disable User Interactions

Set the Enabled property to false to ignore user interactions.

<button type="button" @onclick="@(() => ToggleTreeViewEnabled())">Enable/Disable TreeView</button>

<DxTreeView Enabled="@TreeViewEnabled">
    <Nodes>
        <DxTreeViewNode Text="Metals">
            <Nodes>
                <DxTreeViewNode Text="Alkali metals" />
                <DxTreeViewNode Text="Inner transition elements">
                    <Nodes>
                        <DxTreeViewNode Text="Lanthanides" />
                        <DxTreeViewNode Text="Actinides" />
                    </Nodes>
                </DxTreeViewNode>
            </Nodes>
        </DxTreeViewNode>
    </Nodes>
</DxTreeView>

@code  {
    bool TreeViewEnabled { get; set; } = false;

    void ToggleTreeViewEnabled() { TreeViewEnabled = !TreeViewEnabled; }
}

Load Child Nodes on Demand

When the LoadChildNodesOnDemand option is set to true, the component does not load child nodes until a parent node is expanded for the first time. This optimizes performance for complex hierarchical structures because the TreeView requests the required data from the data source.

You can load child nodes on demand in either bound or unbound modes. In bound mode, the HasChildren property is required. This property specifies whether a TreeView node has child nodes. The component uses the HasChildren property value to render nodes before they are expanded for the first time. If you do not specify this property, users do not see TreeView child nodes in the UI.

<DxTreeView @ref="@treeView"
            CssClass="cw-480"
            Data="@DataSource"
            LoadChildNodesOnDemand="true">
    <DataMappings>
        <DxTreeViewDataMapping HasChildren="HasSubGroups"
                               Children="SubGroups"
                               Text="Title"/>
    </DataMappings>
</DxTreeView>

@code {
    DxTreeView treeView;

    IEnumerable<DateTimeGroup> DataSource = new List<DateTimeGroup>() {
        new DateTimeGroup(new DateTime(DateTime.Now.Year, 1, 1), DateTimeGroupType.Year)
    };

    protected override void OnAfterRender(bool firstRender) {
        if(firstRender) {
            var todayDate = DateTime.Now;
            treeView.SetNodeExpanded(n => n.Text == todayDate.Year.ToString(), true);
        }
        base.OnAfterRender(firstRender);
    }
}

Note that you cannot operate with unloaded nodes in code (for instance, select an unloaded node, get node information, and so on).

Run Demo: TreeView - Load Child Nodes on Demand Mode

Templates

Use the following <DxTreeView> properties to specify a common node template and a text template for all nodes:

In unbound mode, you can create node templates on an individual basis. These templates have a priority over common templates. Use the following <DxTreeViewNode> properties:

<DxTreeView @ref="@treeView"
            Data="@ComponentsData.ComponentSets" >
    <DataMappings>
            <DxTreeViewDataMapping Children="ComponentSets" />
    </DataMappings>
    <NodeTextTemplate>
        @{
            var dataItem = (ComponentSet)context.DataItem;
        }
        @if (!context.IsLeaf) {
            <h5 class="mt-0  d-inline-block">@dataItem.Title</h5>
        }
        else {
            <div class="media-body">
                <h5 class="mt-0">@dataItem.Title</h5>
                @dataItem.Description
            </div>
        }
    </NodeTextTemplate>
</DxTreeView>

@code {
    DxTreeView treeView;
    string GetIconUrl(ComponentSet nodeDataItem) {
        string name = treeView.GetNodeExpanded(n => n.DataItem == nodeDataItem) ? "down" : "right";
        return $"_content/DevExpress.Blazor/dx-blazor.svg#dx-chevron-{name}";
    }
    protected override Task OnAfterRenderAsync(bool firstRender) {
        if(firstRender)
            treeView.ExpandAll();
        return base.OnAfterRenderAsync(firstRender);
    }
}

TreeView Templates

Run Demo: TreeView - Templates

Use the NavigateUrl property to specify a URL where the client web browser navigates when a node is clicked. To specify where to display the URL (in the current window, new tab, and so on), use one of the properties below.

The DxTreeView.Target property specifies the common target attribute’s value for all nodes in the TreeView. To override the attribute value for a specific node, use the DxTreeViewNode.Target property.

The code below sets the common target attribute’s value for all nodes to _blank and overrides this value for the first node (sets it to _self).

<DxTreeView Target="_blank">
    <Nodes>
        <DxTreeViewNode Name="Overview" 
                        Text="Overview" 
                        NavigateUrl="https://demos.devexpress.com/blazor/" 
                        Target="_self"/>
        <DxTreeViewNode Name="Editors" Text="Data Editors" Expanded="true">
            <Nodes>
                <DxTreeViewNode Text="Combobox" NavigateUrl="https://demos.devexpress.com/blazor/ComboBox" />
                <DxTreeViewNode Text="Spin Edit" NavigateUrl="https://demos.devexpress.com/blazor/SpinEdit" />
            </Nodes>
        </DxTreeViewNode>
    </Nodes>
</DxTreeView>

Troubleshooting

If a Blazor application throws unexpected exceptions, refer to the following help topic: Troubleshooting.

Inheritance

Object
ComponentBase
DevExpress.Blazor.Base.DxAsyncDisposableComponent
DevExpress.Blazor.Base.DxDecoratedComponent
DxComponentBase
DxComponentBase<DevExpress.Blazor.Internal.JSInterop.TreeViewJSInteropProxy>
DxControlComponent<DxTreeView, DevExpress.Blazor.Internal.JSInterop.TreeViewJSInteropProxy>
DxNavigationControlComponent<DxTreeView, DevExpress.Blazor.Internal.JSInterop.TreeViewJSInteropProxy>
DxTreeView
See Also