Tree View
The tree view control can present hierarchical data and allows item selection. The items are templated so you can customise how they are displayed.
There are two data sources: the main items source for the control, this gives the root of the hierarchical data. Then there is the items source in the item template which allows the control to list the next level in the hierarchical data.
Example
This example uses a MVVM pattern view model to hold some hierarchical data based on a C# node class. In this example, there is a single root node in the Nodes
collection of the view model:
<TreeView ItemsSource="{Binding Nodes}">
<TreeView.ItemTemplate>
<TreeDataTemplate ItemsSource="{Binding SubNodes}">
<TextBlock Text="{Binding Title}"/>
</TreeDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
C# View Model
using AvaloniaControls.Models;
using System.Collections.ObjectModel;
namespace AvaloniaControls.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
public ObservableCollection<Node> Nodes{ get; }
public MainWindowViewModel()
{
Nodes = new ObservableCollection<Node>
{
new Node("Animals", new ObservableCollection<Node>
{
new Node("Mammals", new ObservableCollection<Node>
{
new Node("Lion"), new Node("Cat"), new Node("Zebra")
})
})
};
}
}
}
C# Node Class
using System.Collections.ObjectModel;
namespace AvaloniaControls.Models
{
public class Node
{
public ObservableCollection<Node>? SubNodes { get; }
public string Title { get; }
public Node(string title)
{
Title = title;
}
public Node(string title, ObservableCollection<Node> subNodes)
{
Title = title;
SubNodes = subNodes;
}
}
}