Creating a Hierarchical 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
TreeDataGridThe control which can be instantiated from XAML or from code and describes how the
TreeDataGridwill 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; }
public ObservableCollection<Person> Children { get; } = new();
}First we create a MainWindowViewModel containing our simple dataset:
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.
The TreeDataGrid source
TreeDataGrid sourceThe source defines how to map the data model to rows and columns. Because we're displaying hierarchical data, we'll use a HierarchicalTreeDataGridSource<Person>. HierarchicalTreeDataGridSource is a generic class where the type parameter represents the data model type, in this case Person.
The constructor to HierarchicalTreeDataGridSource accepts a collection of type IEnumerable<T> to which we'll pass our data set.
We'll create the source in the MainWindowViewModel constructor, add three columns, and expose the source in a property:
The first column above is defined as a HierarchicalExpanderColumn. Its first constructor parameter defines how the data in the column will be displayed. For this we're using a TextColumn - see below for details of its constructor parameters. The second parameter to the HierarchicalExpanderColumn constructor is a lambda which selects the property which will contain the children of each row.
The remaining columns are also defined as TextColumns - again, TextColumn is a generic class that accepts the data model type and a value type. The first parameter to TextColumn is the header to display in the column and the second parameter is a lambda expression which selects the value to display from the data model.
The TreeDataGrid control
TreeDataGrid controlIt's now time to add the TreeDataGrid control to a window and bind it to the source.
Run the Application
Run the application and you should see the data appear:

最后更新于
这有帮助吗?