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.

  1. Open your project.

  2. On the left vertical tool window bar, click nuget icon.

    Troubleshooting

    If you cannot find the icon:

    1. If you never used the nuget icon, it will be under the three dots ... icon.

    2. Alternatively: On the Explorer tab, right-click on your project name and click nuget Manage NuGet Packages.

  3. Search for avalonia controls.

  4. Click Avalonia.Controls.DataGrid.

  5. On the right, click icon. A new window will pop up.

  6. Click Install.

    Troubleshooting

    If you get the error Install failed ... detected package downgrade:

    Then the Avalonia.Controls.DataGrid version does not match the base Avalonia framework version, e.g., if DataGrid is newer than the Avalonia template.

    Upgrade the template or upgrade .NET packages in the project in this case and try installing DataGrid again.

    You will get a message about Avalonia.Controls.DataGrid ... was successfully installed to ....

Now you can close the NuGet window by clicking nuget again.

Integrating a DataGrid into the project#

  1. Open App.axaml and append the <Styleinclude line after <FluentTheme>. After the modification the Styleinclude line should look as follows:

    <Application.Styles>
        <FluentTheme />
        <StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml" />
    </Application.Styles>
    

    We need this, because DataGrid uses additional styles compared to the standard GUI elements.

  2. Open MainWindow.axaml.cs and add the following class under the definition of MainWindow class.

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    Notice the get and set keywords for each field that we did not use before. These keywords introduce methods in the background that are used to get & set FirstName and LastName. We need them; otherwise the GUI framework does not show any data. For example, if you remove {get; set;} from LastName, then you will see no LastName field later when you run the program.

    We will call a field with get or set property.

    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.

  3. 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 ObservableCollection available. ObservableCollection is a special List that can communicate with the GUI when data in the list is modified.

    Warning

    Use ObservableCollection instead of List if you plan to present a list on the GUI.

  4. In MainWindow.axaml.cs, add the following property to the MainWindow class.

        public ObservableCollection<Person> People { get; set; } =
        [
            new()
            {
                FirstName = "Melitta",
                LastName = "Lipp"
            },
            new()
            {
                FirstName = "Heilos",
                LastName = "König"
            },
            new()
            {
                FirstName = "Onur",
                LastName = "Kuştepe"
            }
        ];
    
  5. In MainWindow.axaml.cs, set the DataContext to MainWindow by adding a line to the constructor method MainWindow() as follows:

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }
    

    The DataContext determines which properties (fields with get or set) are available in the XAML file. To make People available in the XAML file as the data source for the DataGrid, we require this file.

  6. Open MainWindow.axaml. Add the following lines between x:Class and Title in the Window tag:

    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>
    
  7. In MainWindow.axaml replace the text Welcome 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 People binds People to the DataGrid so that the data on the GUI is updated automatically, when the data changes and vice-versa.

    • AutoGenerateColumns generates columns automatically by reading the properties of a class, e.g., FirstName and LastName in Person.

    • Other four attributes including Margin configure the style.

    For more information about the attributes, refer to DataGrid documentation.

  8. Run your project.

  9. Try:

    • modifying data

    • changing sort order

  10. 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.

Adding a button#

We already integrated a button in section Getting input from the GUI. Let us integrate a button that adds new data to the list:

  1. Add a button to the XAML:

        <StackPanel>
            <Button Click="NewRowButton_OnClick">New row</Button>
            <DataGrid Margin="20" ItemsSource="{Binding People}"
                      AutoGenerateColumns="True"
                      GridLinesVisibility="All"
                      BorderThickness="1" BorderBrush="Gray" />
        </StackPanel>
    
  2. Add the click handler in the MainWindow class:

        public void NewRowButton_OnClick(object? sender, RoutedEventArgs e)
        {
            People.Add(new Person { FirstName = "First", LastName = "Last" });
        }
    }
    
  3. Run the project. The button should add new rows that you can edit.

You can find the whole project here:

Activity 39 (Person queue)

Create a GUI app that can check a list of persons and puts them into two categories based on two buttons:

  • ⬅️

  • ➡️

You can augment your test code above so that you have one list above and two lists below that are horizontally aligned.