Creating a Flat TreeDataGrid
There are two parts to any TreeDataGrid
:
- The "Source" which is defined in code and describes how your data model will map to the rows and columns of the
TreeDataGrid
- The control which can be instantiated from XAML or from code and describes how the
TreeDataGrid
will appear
The source is usually defined at the view model layer if you're using the MVVM pattern but can also be defined in code-behind. This introduction will assume that you're using the MVVM pattern.
This article assumes that you are using C# 10 and have nullable reference types enabled.
Installation
First follow the installation instructions, ensuring that you add the theme to your App.axaml
file.
The Data Model
The data model is your "source" data that will be displayed in the TreeDataGrid
and will be specific to your application. For this introduction we will be using a very simple Person
class:
public class Person
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public int Age { get; set; }
}
First we create a MainWindowViewModel
containing our simple dataset:
using System.Collections.ObjectModel;
using Avalonia.Controls;
using Avalonia.Controls.Models.TreeDataGrid;
public class MainWindowViewModel
{
private ObservableCollection<Person> _people = new()
{
new Person { FirstName = "Eleanor", LastName = "Pope", Age = 32 },
new Person { FirstName = "Jeremy", LastName = "Navarro", Age = 74 },
new Person { FirstName = "Lailah ", LastName = "Velazquez", Age = 16 },
new Person { FirstName = "Jazmine", LastName = "Schroeder", Age = 52 },
};
}
We store the data in an ObservableCollection<T>
which will allow the TreeDataGrid
to listen for changes in the data and automatically update the UI.