TreeView
The TreeView is a control that presents hierarchical tree data and allows selection of it.
One example for populating a TreeView can be from a directory on the computer. You can create a TreeView in the MainWindow.axaml file in an Avalonia MVVM project.
1
<TreeView Items="{Binding Items}"
2
Width="400" Height="480"
3
HorizontalAlignment="Left"
4
<TreeView.ItemTemplate>
5
<TreeDataTemplate ItemsSource="{Binding Subfolders}">
6
<TextBlock Text="{Binding strNodeText}"/>
7
</TreeDataTemplate>
8
</TreeView.ItemTemplate>
9
</TreeView>
Copied!
In the MainWindowViewModel.cs you can add this code which will recursively look up all the subfolders and populate the TreeView from Items and Subfolders
1
public ObservableCollection<Node> Items { get; }
2
public ObservableCollection<Node> SelectedItems { get; }
3
public string strFolder { get; set; }
4
​
5
public MainWindowViewModel()
6
{
7
strFolder = @"C:\Users\hooty\Desktop"; // EDIT THIS FOR AN EXISTING FOLDER
8
​
9
Items = new ObservableCollection<Node>();
10
​
11
Node rootNode = new Node(strFolder);
12
rootNode.Subfolders = GetSubfolders(strFolder);
13
14
Items.Add(rootNode);
15
}
16
​
17
public ObservableCollection<Node> GetSubfolders(string strPath)
18
{
19
ObservableCollection<Node> subfolders = new ObservableCollection<Node>();
20
string[] subdirs = Directory.GetDirectories(strPath, "*", SearchOption.TopDirectoryOnly);
21
​
22
foreach (string dir in subdirs)
23
{
24
Node thisnode = new Node(dir);
25
​
26
if (Directory.GetDirectories(dir, "*", SearchOption.TopDirectoryOnly).Length > 0)
27
{
28
thisnode.Subfolders = new ObservableCollection<Node>();
29
​
30
thisnode.Subfolders = GetSubfolders(dir);
31
}
32
​
33
subfolders.Add(thisnode);
34
}
35
​
36
return subfolders;
37
}
38
​
39
public class Node
40
{
41
public ObservableCollection<Node> Subfolders { get; set; }
42
​
43
public string strNodeText { get; }
44
public string strFullPath { get; }
45
​
46
public Node(string _strFullPath)
47
{
48
strFullPath = _strFullPath;
49
strNodeText = Path.GetFileName(_strFullPath);
50
}
51
}
Copied!
The example project source can be found at avalonia-treeview-test​

Reference

​TreeView​

Source code

​TreeView.cs​
Export as PDF
Copy link
Edit on GitHub