Home > Net >  Binding ViewModel to View through View ctor makes Maui app crash
Binding ViewModel to View through View ctor makes Maui app crash

Time:10-27

When I launch my app I get the following message:

An unhandled win32 exception occured in MauiApp.exe

Unfortunately I am not able to get a detailed exception message, as the application crashes and "the debugger is not configured to debug this unhandled exception". I have isolated the issue and it occurs whenever I bound my View to a ViewModel like so:

public partial class MainPage : ContentPage
{
    public MainPage(MainViewModel mainViewModel)
    {
        BindingContext = mainViewModel;
        InitializeComponent();

    }
}

public sealed class MainViewModel
{
   
}

And in the MauiProgram.cs file:

builder.Services.AddTransient<MainViewModel>();

How can I resolve this issue?

CodePudding user response:

Put the creation, after initialization:

    InitializeComponent();
    BindingContext = mainViewModel;

CodePudding user response:

I tested the code on my side and I found the issue. You should add the following codes in the MauiProgram.cs file, not only register the MainViewModel but also register the MainPage.

builder.Services.AddTransient<MainViewModel>();
builder.Services.AddTransient<MainPage>();
  • Related