avaloniauiavalonia

Avalonia DataGrid example populating at design time, but not at runtime


I'm probably missing something very basic - I'm new to Avalonia, MVVM, and xaml.

I'm trying to get this DataGrid example running: https://docs.avaloniaui.net/docs/reference/controls/datagrid/

In the 'Window' tag I have: xmlns:vm="using:AvaloniaControls.ViewModels"

Here is the xaml to create the DataGrid:

<DataGrid Name="TestGrid" x:DataType="vm:MainWindowViewModel" ItemsSource="{Binding People}" IsReadOnly="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
        <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" />
    </DataGrid.Columns>
</DataGrid>

The grid is correctly populated with the test data at design time by including this near the top of the axaml file:

<Design.DataContext>
    <vm:MainWindowViewModel/>
</Design.DataContext>

However, the grid doesn't populate at runtime.

Here is the MainWindowViewModel class (from the online example):

using System.Collections.ObjectModel;
using System.Collections.Generic;

namespace AvaloniaControls.ViewModels
{
    public class MainWindowViewModel : ViewModelBase
    {
        public ObservableCollection<Person> People { get; }

        public MainWindowViewModel()
        {
            var people = new List<Person>
            {
                new Person("Neil", "Armstrong"),
                new Person("Buzz", "Lightyear"),
                new Person("James", "Kirk")
            };
            People = new ObservableCollection<Person>(people);
        }
    }

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

        public Person(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }
    }
}

Solution

  • After looking at the Design.DataContext block, I happened to try following in C# code-behind:

    var test = new AvaloniaMVVM.ViewModels.MainWindowViewModel();
    TestGrid.DataContext = test;
    

    It works now - I think this really should have been in the documentation example. Probably obvious to those with MVVM experience though.