Tutorial
Setup
TreeView is relatively easy to set up. As with many other components, it require a list of items (ItemsSource
parameter) to be specified and a type of the items (T
type parameter).
There is only one requirement, that in order for a class to be rendered inside TreeView, it is necessary to implement ITreeNode
interface.
This interface consist only of 2 members: IsExpanded
and Children
and tells the component whether to render sub items (expanded or collapsed) and list of sub items.
razor
<TreeView T="Child" ItemsSource="Tree" /> @code { List<Child> Tree { get; set; } = new(); class Child : ITreeNode<Child> { public string Title { get; set; } = ""; public IList<Child> Children { get; set; } = new List<Child>(); public bool IsExpanded { get; set; } public override string ToString() => Title; } }
Adding sub items
Adding items is straightforward as it is only necessary to add new items to Children
property.
Example
razor
protected void AddItems() { var grandChildren = new List<Child> { new Child { Title = "Grandchild A" }, new Child { Title = "Grandchild B" }, }; var children = new List<Child> { new Child { Title = "Child A" }, new Child { Title = "Child B", Children = grandChildren }, }; Tree.Add(new Child { Title = "Parent A", Children = children }); Tree.Add(new Child { Title = "Parent B" }); }