Presenting data on a grid#
Data grid with a button for adding new rows and sorting.
We will integrate DataGrid – a GUI control component for presenting class data similar to the data represented on a spreadsheet.
Creating a project#
First create a new Avalionia .NET App with the name DataGridExample.
DataGrid control installation#
In the following, we will install Avalonia.Controls.DataGrid in a C# project.
Open your project.
Search for
avalonia controls.Click
Avalonia.Controls.DataGrid.On the right, click
icon. A new window will pop up.
Click
Install.TroubleshootingIf you get the error
Install failed ... detected package downgrade:Then the
Avalonia.Controls.DataGridversion does not match the baseAvaloniaframework version, e.g., ifDataGridis newer than theAvaloniatemplate.Upgrade the template or upgrade .NET packages in the project in this case and try installing
DataGridagain.You will get a message about
Avalonia.Controls.DataGrid ... was successfully installed to ....
Integrating a DataGrid into the project#
-
Open
App.axamland append the<Styleincludeline after<FluentTheme>. After the modification theStyleincludeline should look as follows:<Application.Styles> <FluentTheme /> <StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml" /> </Application.Styles>
We need this, because
DataGriduses additional styles compared to the standard GUI elements. Open
MainWindow.axaml.csand add the following class under the definition ofMainWindowclass.public class Person { public string FirstName { get; set; } public string LastName { get; set; } }
Notice the
getandsetkeywords for each field that we did not use before. These keywords introduce methods in the background that are used to get & setFirstNameandLastName. We need them; otherwise the GUI framework does not show any data. For example, if you remove{get; set;}fromLastName, then you will see noLastNamefield later when you run the program.We will call a field with
getorsetproperty.The reason for the behavior in the last paragraph could be that C# has a feature which allows to get the fields with get and set methods automatically, which in turn is used to show these data in DataGrid.
Open
MainWindow.axaml.cs.Add the following line on the top of the file:
using System.Collections.ObjectModel;
This library is required to make the
ObservableCollectionavailable.ObservableCollectionis a specialListthat can communicate with the GUI when data in the list is modified.Warning
Use
ObservableCollectioninstead ofListif you plan to present a list on the GUI.In
MainWindow.axaml.cs, add the following property to theMainWindowclass.public ObservableCollection<Person> People { get; set; } = [ new() { FirstName = "Melitta", LastName = "Lipp" }, new() { FirstName = "Heilos", LastName = "König" }, new() { FirstName = "Onur", LastName = "Kuştepe" } ];
In
MainWindow.axaml.cs, set theDataContexttoMainWindowby adding a line to the constructor methodMainWindow()as follows:public MainWindow() { InitializeComponent(); DataContext = this; }
The
DataContextdetermines which properties (fields with get or set) are available in the XAML file. To makePeopleavailable in the XAML file as the data source for theDataGrid, we require this file.Open
MainWindow.axaml. Add the following lines betweenx:ClassandTitlein theWindowtag:xmlns:local="clr-namespace:YOUR-PROJECT-NAME" x:DataType="local:MainWindow"
For example:
x:Class="DataGridExample.MainWindow" xmlns:local="clr-namespace:DataGridExample" x:DataType="local:MainWindow" Title="DataGridExample"> <StackPanel> <Button Click="NewRowButton_OnClick">New row</Button>
In
MainWindow.axamlreplace the textWelcome to Avalonia!with the following block:<DataGrid Margin="20" ItemsSource="{Binding People}" AutoGenerateColumns="True" GridLinesVisibility="All" BorderThickness="1" BorderBrush="Gray"> </DataGrid>
These lines ensure the following:
Binding PeoplebindsPeopleto theDataGridso that the data on the GUI is updated automatically, when the data changes and vice-versa.AutoGenerateColumnsgenerates columns automatically by reading the properties of a class, e.g.,FirstNameandLastNameinPerson.Other four attributes including
Marginconfigure the style.
For more information about the attributes, refer to
DataGriddocumentation.Run your project.
Try:
modifying data
changing sort order
If you would like to add additional logic, then append them to the
MainWindow()method, e.g.,People.RemoveAt(0);will remove an item from the top of the collection.