# Blazor TreeView

URL: https://flexcoreui.com/demo/tree/treeview-explorer  
Section: Components  
Controls: TreeViewControl, TreeNode  
Keywords: treeview, tree view, hierarchical tree, VB6 treeview, checkbox tree

Show nested data in a Blazor tree view: a searchable staff directory with a node inspector, checkboxes with partly checked parents, and a classic VB6 look.

## Documentation

### Parameters

| Name | Type | Default | Description |
|---|---|---|---|
| Nodes | List<TreeNode>? | null | Root nodes; each carries its Children. A null list is replaced by an empty one on first use. Ids must be non-empty and unique across the tree, or the control throws. |
| SelectedNode / SelectedNodeChanged | TreeNode? | null | The primary selected node, two-way. Setting it selects the node with that Id and clears the others unless AllowMultiSelect is on. Ignored while SelectedNodeIds is set, which then supplies it. |
| SelectedNodeIds / CheckedNodeIds / ExpandedNodeIds | IReadOnlyList<string>? | null | Id lists that drive selection, checks and expansion, each with a …Changed callback. Applied when the sequence changes; null leaves the node flags alone. |
| OnNodeClick / OnNodeDoubleClick / OnNodeActivated / OnNodeExpand | EventCallback<TreeNode> |  | OnNodeClick follows a click, after the selection. OnNodeDoubleClick follows a double-click, and Enter when OnNodeActivated has no handler; OnNodeActivated is raised by Enter only. OnNodeExpand is raised when a single node becomes expanded, after any lazy load; ExpandAllAsync does not raise it. |
| ToggleOnNodeClick | bool | true | A plain click on a parent expands or collapses it before selecting it; a Ctrl, Cmd or Shift click only selects. The expander arrow toggles regardless. |
| ShowIcons | bool | true | Draws each node's IconCss (ExpandedIconCss while expanded). With the VB6 style a parent without its own icon gets a folder in FolderStyle and a leaf a spacer; the Standard style draws nothing for a node without IconCss. |
| FolderStyle | TreeFolderStyle | TreeFolderStyle.Yellow | Yellow, Grey or None. Read only when the VB6 style is on; it picks the root modifier class and the folder icon. |
| UseVb6TreeStyle | bool | false | Dotted connector lines and plus/minus boxes, as in the Windows common control. A CssClass containing fx-treeview-vb6 turns it on too. |
| TreeIndentPixels | int | 16 | Indent per level in the VB6 and Outline styles. The Standard style without VB6 lines ignores it and indents 20px per level. |
| ShowCheckboxes / AutoCheck | bool | false | A checkbox per node in the Standard display mode (Outline rows draw none, though aria-checked and Space still apply); Space toggles the focused one. AutoCheck cascades a check down to the children and sets each parent checked or indeterminate from its children. |
| AllowMultiSelect | bool | false | Ctrl-click toggles a node, Shift-click selects the visible range from the last node selected without Shift, Ctrl+A selects every visible node. Off, a click or Space selects one node. |
| Height / CssClass | string? | null | Height sizes the root with overflow:auto; CssClass is appended to the root element. |
| TabIndex | int | 0 | The tabindex of the root element, the tree's only tab stop. |
| AriaLabel | string | "Tree" | The aria-label of the root element. |
| FocusOnSelection | bool | true | After a selection or a reveal the root element takes focus again, without scrolling. Turn off when the page must keep focus in another input. |
| DisplayMode | TreeViewDisplayMode | TreeViewDisplayMode.Standard | Standard is the classic tree. Outline draws status circles and dots, a connector rail, the node's Caption, SecondaryText, SecondaryIcon and BadgeText, and a chevron on the right. |
| ShowSearchBox | bool | false | Shows a search box above the tree whose text filters the nodes as you type. FilterText wins when both are set. |
| SearchPlaceholder | string | "Search" | Placeholder and aria-label of the search box. |
| SearchText / SearchTextChanged | string? | null | The search box text, two-way; it filters even while the box is hidden. A node stays visible when its Text contains the filter, ignoring case (current culture), or when a descendant does; the branches above a match are shown expanded whatever their IsExpanded. The children of a matching group are hidden unless they match too, and nodes cannot be expanded or collapsed while a filter is active. Whitespace only means no filter. |
| FilterText | string? | null | A filter set by the page. It takes precedence over the search box text and matches the same way. |
| EmptyFilterText | string | "No matches" | Shown in a status region under the tree when the search box filter matches nothing. Only with ShowSearchBox: a host FilterText that matches nothing leaves the tree empty, as before. |
| AllowEditing | bool | false | F2 or a double-click opens an inline rename with Save and Cancel buttons; Enter commits, Escape cancels, an empty name is refused. Not shown on this page. |
| NodeEditing / NodeEditCommitting / NodeEdited | EventCallback<TreeNodeEditEventArgs> |  | Before the editor opens, before the new text is applied, and after it. Cancel vetoes the first two; Error on the second shows the message instead of committing. |
| AllowDragAndDrop | bool | false | Nodes become draggable; dropping one on another moves it inside that node as its last child. Not shown on this page. |
| CanDrop | Func<TreeNodeMoveEventArgs, bool>? | null | Asked before NodeMoving; false refuses the move without raising it. |
| NodeMoving / NodeMoved | EventCallback<TreeNodeMoveEventArgs> |  | Before and after a move, by drop or by MoveNodeAsync; Cancel on the first vetoes it. |
| EnableVirtualization | bool | false | Row windowing through Virtualize with four rows of overscan; every row is forced to ItemSize high. |
| ItemSize | float | 32 | Row height in px, used for virtualization and for scrolling a revealed row into view. Below 20 the control throws. |
| LoadChildren | Func<TreeNode, CancellationToken, Task<IReadOnlyList<TreeNode>>>? | null | Called the first time a node with HasUnloadedChildren expands, and for such nodes that start expanded; the result replaces its Children. A failure collapses the node and reports through Error. |
| NodeTemplate | RenderFragment<TreeNode>? | null | Replaces the node text; key presses inside it do not reach the tree. |
| NodeComparer | IComparer<TreeNode>? | null | Sorts the siblings at every level. |
| NodesChanged | EventCallback<List<TreeNode>> |  | Raised with the root list after a single node expands or collapses (not ExpandAllAsync or CollapseAllAsync), a committed rename, and AddNodeAsync, RemoveNodeAsync or MoveNodeAsync. |
| Error | EventCallback<string> |  | Raised with the message of a failed lazy load, rename or move; the same message appears in an alert under the tree. |

### Node

| Name | Type | Default | Description |
|---|---|---|---|
| Id | string |  | Key; defaults to a random 8-character string. Must be non-empty and unique in the tree. |
| Text | string | "" | Label. It is also the row's accessible name and what the filter and type-ahead match. |
| IconCss / ExpandedIconCss | string? | null | Leaf or folder icon classes; the second is used while expanded. |
| IsExpanded / IsSelected / IsChecked / IsDisabled / IsBold | bool | false | State flags. A disabled node is skipped by the keyboard and cannot be selected, checked, renamed or moved. IsIndeterminate is set by the control. |
| Children | List<TreeNode> | new() | Child nodes. HasChildren is true when there are any, or when children are still to load. |
| HasUnloadedChildren | bool | false | Marks a node whose children come from LoadChildren on first expand; cleared once loaded. |
| Tag | object? | null | Your own payload. |
| Status | TreeNodeStatus |  | Outline mode only; starts as None, which draws no mark. NotStarted, InProgress and Complete draw a circle on a group and a dot on the rail of an item. TreeViewData.RollUpStatus sets parents from their children. |
| Caption | string? | null | Outline mode only: a small line above the text. |
| SecondaryText / SecondaryIcon | string? | null | Outline mode only: a second line under the text, with an icon before it given as a FlexIcons name or raw SVG path data. |
| BadgeText | string? | null | Outline mode only: a right-aligned label after the text. RollUpStatus with setBadges writes a done/total count here. |

### Methods

| Name | Type | Description |
|---|---|---|
| SelectNodesAsync(IEnumerable<string> ids) | Task | Selects those nodes: only the first without AllowMultiSelect, and never a disabled one. Raises SelectedNodeChanged for the first and the selection callbacks. |
| SetCheckedAsync(string id, bool value) | Task | Checks or unchecks one node, cascading with AutoCheck. Ignored for a disabled or unknown node. |
| CheckAllAsync(bool value = true) | Task | Checks every enabled node, or unchecks them with false, as Add everything and Clear do in the second example. |
| SetExpandedAsync(string id, bool expanded) | Task | Expands or collapses one node, first loading its children through LoadChildren when they are not loaded yet. |
| ExpandAllAsync(bool loadChildren = false) | Task | Expands every enabled branch whose children are known; with true it also loads the lazy branches, one at a time. |
| CollapseAllAsync() | Task | Collapses every node, including branches still loading. |
| EnsureVisibleAsync(string id) | Task | Expands the node's ancestors, then focuses and scrolls to it. Throws for an unknown node, or one the current filter hides. |
| BeginEditAsync(string id) / CommitEditAsync() / CancelEditAsync() | Task | Open, save or close the inline rename, as F2, Enter and Escape do; only with AllowEditing. Opening raises NodeEditing, which can cancel; saving refuses an empty name, then raises NodeEditCommitting and NodeEdited. |
| AddNodeAsync(TreeNode node, string? parentId = null) | Task | Adds a node at the end of the roots, or of that parent's children. Throws for an unknown parent, or one whose children are not loaded yet. |
| RemoveNodeAsync(string id) | Task | Removes the node with its children. Ignored for a disabled or unknown node. |
| MoveNodeAsync(string id, string targetId, TreeDropPosition position = Inside) | Task | Moves a node as a drop does: CanDrop and NodeMoving can refuse it, then NodeMoved is raised. Throws for an unknown node. |

### Keys

| Name | Description |
|---|---|
| Tab | Enters or leaves the tree. The root element is the single tab stop; the current node is named through aria-activedescendant and outlined while the tree has focus. Expander arrows and checkboxes are not tab stops. |
| Down / Up arrow | Moves to the next or previous visible enabled node and selects it. With Ctrl or Cmd only the focus moves; with Shift and AllowMultiSelect the selection extends. |
| Right arrow | On a collapsed parent, expands it. On an expanded parent, moves to its first child. On a leaf, nothing. |
| Left arrow | On an expanded node, collapses it. Otherwise moves to the parent; on a collapsed root it stays. |
| Home / End | First or last visible node, selected unless Ctrl or Cmd is held. |
| Space | With ShowCheckboxes, toggles the focused node's check (an indeterminate node becomes checked). Otherwise selects the focused node with the Ctrl and Shift rules of a click. |
| Enter | Raises OnNodeActivated, or OnNodeDoubleClick when no activated handler is set. It does not expand the node or start a rename. |
| F2 | Starts an inline rename when AllowEditing is on; otherwise nothing. |
| Ctrl+A / Cmd+A | With AllowMultiSelect, selects every visible enabled node. |
| A printable character | Type-ahead: moves to the next visible node after the current one whose Text starts with that character, ignoring case, wrapping to the top, and selects it. One character at a time, no multi-character buffer. With Ctrl or Alt held the key is ignored. |
| Enter / Escape in the rename box | Commit or cancel the rename. While the box is open the tree ignores every other key. |

### Aria

| Name | Description |
|---|---|
| role tree | The root div, with tabindex from TabIndex, aria-label from AriaLabel and aria-multiselectable true or false from AllowMultiSelect. The key handler is here. |
| aria-activedescendant | On the root: the element id of the current node, so one tab stop serves the whole tree. Omitted only when no enabled node is visible. |
| role treeitem | Every visible row. The rows are flat children of the tree, not nested. The row's aria-label is the node Text, so a template, caption, secondary line or badge is not part of its name. |
| aria-level / aria-posinset / aria-setsize | On every row: depth from 1, position among the siblings from 1, and the sibling count. They carry the hierarchy, since the rows are not nested. |
| aria-expanded | true or false on a row with children, or with children still to load; omitted on a leaf. While a filter is active it reflects the filtered view, not IsExpanded. |
| aria-selected | true or false on every row, from IsSelected. |
| aria-checked | Only with ShowCheckboxes: mixed, true or false on the row. In the Standard mode the checkbox input inside repeats it and has tabindex -1. |
| aria-disabled | true or false on every row, from IsDisabled. |
| aria-busy | true on a row while LoadChildren runs for it, with a role status span reading Loading… in the row; omitted otherwise. |
| role button | The expander arrow of a parent in Standard mode and the chevron in Outline mode, labeled Expand or Collapse plus the node text. Neither is focusable; they are mouse targets. A leaf's arrow is aria-hidden. |
| aria-hidden | Node icons, status circles and dots, the rail and leaf arrows. |
| role search | The wrapper of the built-in search box; the input is type=search with aria-label from SearchPlaceholder. |
| role status | The EmptyFilterText message when the search box filter matches nothing, and the Loading… span of a lazy row. |
| role alert | The AlertControl that shows an Error message under the tree. |
| Rename box | The inline editor's input is labeled Rename node; Save and Cancel are buttons. |
| Not emitted | No role group around children and no aria-owns; the hierarchy is in the level, posinset and setsize attributes only. No aria-describedby or aria-current. |

## Examples

### Explorer

```razor
@using Fx.ControlKit

<ButtonGroupControl Items="_styleItems" @bind-Values="_styleValues" Selection="ChoiceSelectionMode.Single" Enabled="@_useVb6Style" AriaLabel="Folder style" />
<ToggleButtonControl @bind-Selected="_useVb6Style">VB6 lines</ToggleButtonControl>
<ButtonControl CssClass="btn-sm" OnClick="() => _tree!.ExpandAllAsync()">Expand all</ButtonControl>
<ButtonControl CssClass="btn-sm" OnClick="() => _tree!.CollapseAllAsync()">Collapse all</ButtonControl>

<div class="explorer">
    <div class="tree">
        <TreeViewControl @ref="_tree" Nodes="@_treeNodes" ShowSearchBox="true" SearchPlaceholder="Find a person" AriaLabel="Staff directory"
                         SelectedNode="@_selectedNode"
                         SelectedNodeChanged="HandleNodeSelected"
                         ToggleOnNodeClick="true"
                         ShowIcons="true"
                         UseVb6TreeStyle="@_useVb6Style"
                         FolderStyle="@FolderStyle"
                         TreeIndentPixels="16"
                         NodesChanged="TreeChanged" />
    </div>
    <div class="inspector">
        <h4>Selected in the directory</h4>
        @if (_selectedNode is not null)
        {
            <dl class="props">
                <dt>Name</dt><dd><strong>@_selectedNode.Text</strong></dd>
                <dt>Kind</dt><dd>@(_selectedNode.Children.Count > 0 ? "Group" : "Person")</dd>
                <dt>Entries inside</dt><dd>@_selectedNode.Children.Count</dd>
                <dt>Open</dt><dd>@(_selectedNode.IsExpanded ? "yes" : "no")</dd>
                <dt>Details</dt><dd>@(_selectedNode.Tag?.ToString() ?? "none")</dd>
            </dl>
        }
        else
        {
            <p class="muted">Click a person or a group to read it.</p>
        }
    </div>
</div>
```

```csharp
private TreeViewControl? _tree;
private List<TreeNode> _treeNodes = [];

private TreeNode? _selectedNode;

private bool _useVb6Style = true;

// Folder style switch: a ButtonGroupControl bound to the enum's name.
private readonly SelectionItem[] _styleItems = { new("Yellow", "Yellow folders"), new("Grey", "Gray folders"), new("None", "No icons") };

private IReadOnlyList<string> _styleValues = new[] { "Yellow" };

private TreeFolderStyle FolderStyle => Enum.Parse<TreeFolderStyle>(_styleValues[0]);

protected override void OnInitialized()
{
    _treeNodes = BuildSampleTree();
    _selectedNode = _treeNodes.FirstOrDefault();
}

private void HandleNodeSelected(TreeNode node) => _selectedNode = node;
private void TreeChanged(List<TreeNode> _) { }   // an expand or collapse re-renders the card, so Open stays true

private static List<TreeNode> BuildSampleTree()
{
    return
    [
        new TreeNode
        {
            Id = "root-1",
            Text = "Staff Directory",
            IsExpanded = true,
            Tag = "Current staff",
            Children =
            [
                new TreeNode
                {
                    Id = "reservations",
                    Text = "Reservations",
                    IsExpanded = true,
                    Children =
                    [
                        new TreeNode { Id = "hermione-ranger", Text = "Hermione Ranger", Tag = "Team lead, Lisbon office" },
                        new TreeNode { Id = "ron-measly", Text = "Ron Measly", Tag = "Reservations agent, Lisbon office" },
                        new TreeNode { Id = "ginny-measly", Text = "Ginny Measly", Tag = "Reservations agent, Denver office" }
                    ]
                },
                new TreeNode
                {
                    Id = "tour-operations",
                    Text = "Tour Operations",
                    IsExpanded = false,
                    Children =
                    [
                        new TreeNode { Id = "albus-door", Text = "Albus Door", Tag = "Operations planner, Kyoto office" },
                        new TreeNode { Id = "rubeus-haggle", Text = "Rubeus Haggle", Tag = "Supplier coordinator, Cape Town office" },
                        new TreeNode { Id = "luna-goodlove", Text = "Luna Goodlove", Tag = "Guide scheduler, Kyoto office" }
                    ]
                },
                new TreeNode
                {
                    Id = "finance",
                    Text = "Finance",
                    Children =
                    [
                        new TreeNode { Id = "minerva-mcgadget", Text = "Minerva McGadget", Tag = "Finance manager, Denver office" },
                        new TreeNode { Id = "filius-flipwick", Text = "Filius Flipwick", Tag = "Payroll specialist, Denver office" }
                    ]
                }
            ]
        },
        new TreeNode
        {
            Id = "root-2",
            Text = "Joining in December",
            Children =
            [
                new TreeNode { Id = "cedric-diggle", Text = "Cedric Diggle", Tag = "Starts December 1, Lisbon office" },
                new TreeNode { Id = "sybil-treeline", Text = "Sybil Treeline", Tag = "Starts December 7, Denver office" }
            ]
        }
    ];
}
```

### Extras

```razor
@using Fx.ControlKit

<ButtonControl CssClass="btn-sm" OnClick="() => _extrasTree!.CheckAllAsync(true)">Add everything</ButtonControl>
<ButtonControl CssClass="btn-sm" OnClick="() => _extrasTree!.CheckAllAsync(false)">Clear</ButtonControl>

<div class="explorer">
    <div class="tree">
        <TreeViewControl @ref="_extrasTree" Nodes="@_extras" ShowCheckboxes="true" AutoCheck="true" @bind-CheckedNodeIds="_checked"
                         ShowIcons="false" Height="100%" AriaLabel="New-hire extras" />
    </div>
    <div class="inspector" role="status">
        <h4>Onboarding order for Sybil Treeline</h4>
        <dl class="props">
            <dt>Standard kit</dt><dd>$1,450</dd>
            @foreach (var extra in Chosen)
            {
                <dt>@extra.Key</dt><dd>$@extra.Value</dd>
            }
            <dt><strong>Total</strong></dt><dd><strong>@((1450 + Chosen.Sum(e => e.Value)).ToString("C0"))</strong></dd>
        </dl>
    </div>
</div>
```

```csharp
// Extras: the leaf ids are the extras' names, and Prices holds what each one costs
private TreeViewControl? _extrasTree;
private static readonly Dictionary<string, int> Prices = new()
{
    ["Headset"] = 80, ["Second monitor"] = 210, ["Spreadsheet basics"] = 65, ["Customer care workshop"] = 120, ["First aid course"] = 95, ["Transit pass"] = 120,
};
private readonly List<TreeNode> _extras =
[
    new() { Id = "desk-setup", Text = "Desk setup", IsExpanded = true, Children = [Extra("Headset"), Extra("Second monitor")] },
    new() { Id = "training", Text = "Training", IsExpanded = true, Children = [Extra("Spreadsheet basics"), Extra("Customer care workshop"), Extra("First aid course")] },
    Extra("Transit pass"),
];
private IReadOnlyList<string> _checked = new[] { "Headset" };
private static TreeNode Extra(string name) => new() { Id = name, Text = $"{name}, ${Prices[name]}" };
private IEnumerable<KeyValuePair<string, int>> Chosen => Prices.Where(p => _checked.Contains(p.Key));
```

