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?

2

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.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật