Search code examples
c#xamlavaloniauiavalonia

Avalonia DataContext is null in code behind


I have the following application structure:

Views:

  • MainWindow
  • MainView
  • View1
  • View2

ViewModels:

  • MainViewModel

MainWindow:

<Window xmlns="https://github.com/avaloniaui"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="using:Frontend.ViewModels"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:views="clr-namespace:Frontend.Views"
    mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
    x:Class="Frontend.Views.MainWindow"
    Icon="/Assets/avalonia-logo.ico"
    Title="Frontend">

    <views:MainView/>
</Window>

MainView:

<UserControl xmlns="https://github.com/avaloniaui"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:vm="clr-namespace:Frontend.ViewModels"
         xmlns:views="clr-namespace:Frontend.Views"
         mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
         x:Class="Frontend.Views.MainView"
         x:DataType="vm:MainViewModel">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.3*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="0.4*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
    
        <views:View1 Grid.Row="0" Grid.Column="0"/>
        <views:View2 Grid.Row="1" Grid.Column="1"/>
    
    </Grid>

</UserControl>

View1:

<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:vm="clr-namespace:Frontend.ViewModels"
             mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
             x:Class="Frontend.Views.View1"
             x:DataType="vm:MainViewModel">

    <DataGrid Name="TableDataGrid" AutoGenerateColumns="False" IsReadOnly="True" GridLinesVisibility="All"
              CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserSortColumns="True"
              BorderThickness="1" BorderBrush="Gray" VerticalAlignment="Center" HorizontalAlignment="Center"/>

</UserControl>

In View1's codebehind I want to alter the DataGrid, like so:

using Avalonia.Controls;
using Avalonia.Data;
using Frontend.ViewModels;
using System.Data;

namespace Frontend.Views;

public partial class View1 : UserControl
{
    public View1()
    {
        InitializeComponent();
        var viewModel = DataContext as MainViewModel;
        TableDataGrid.ItemsSource = viewModel.TableData.DefaultView;

        foreach (DataColumn x in viewModel.TableData.Columns)
        {
            if (x.DataType == typeof(bool))
            {
                TableDataGrid.Columns.Add(new DataGridCheckBoxColumn { Header = x.ColumnName, Binding = new Binding($"Row.ItemArray[{x.Ordinal}]") });
            }
            else
            {
                TableDataGrid.Columns.Add(new DataGridTextColumn { Header = x.ColumnName, Binding = new Binding($"Row.ItemArray[{x.Ordinal}]") });
            }
        }
    }
}

The problem is that the DataContext is null. As per the Avalonia docs any controls will inherit their parent's DataContext, if they haven't got their own defined. The problem seems to be that the views are being created and the context assigned later, because in View2 I have bindings to MainViewModel's properties and those work fine, without me setting any data context.

So, my question is - how do I make it so the DataGrid can be updated by the codebehind using data from the DataContext?


Solution

  • In this scenario, you will need to handle the DataContextChanged and Initialized events.
    I am writing the example code from my phone, so some minor errors are possible.

            public View1()
            {
                DataContextChanged += OnDataContextChanged;
    
                InitializeComponent();            
            }
    
            private void OnDataContextChanged(object sender, EventArgs e)
            {
                if (IsInitialized)
                {
    
                    var viewModel = DataContext as MainViewModel;
                    TableDataGrid.ItemsSource = viewModel.TableData.DefaultView;
    
                    foreach (DataColumn x in viewModel.TableData.Columns)
                    {
                        if (x.DataType == typeof(bool))
                        {
                            TableDataGrid.Columns.Add(new DataGridCheckBoxColumn { Header = x.ColumnName, Binding = new Binding($"Row.ItemArray[{x.Ordinal}]") });
                        }
                        else
                        {
                            TableDataGrid.Columns.Add(new DataGridTextColumn { Header = x.ColumnName, Binding = new Binding($"Row.ItemArray[{x.Ordinal}]") });
                        }
                    }
                }
                else
                {
                    Initialized += delegate { OnDataContextChanged(sender, e); };
                }
            }
    

    But I would advise you to listen for changes in the DataGrid.ItemsSource property (having previously set the binding) and adjust the columns when it changes.