Álvaro García
Álvaro García

Reputation: 19396

How to open another page if there is an exception in the view model of the main page?

I have a MAUI application with two pages and the two view models for this pages. One is the main page and the other is the settings page.

In the view model of the main page (the first page to show), I need to read some initial data from a database. I want that if there is some problem, open the settings page so the user could check the configuration.

The problem is that if an exception happens in the constructor of the main page, I can't naveigate to the settings page. I have also to try to show a message that tells that it should to check the settings to ensure the cofiguration is correct. The result is always the same, a black screen.

This is my code:

The AppShell.xaml

<Shell
    x:Class="GTS.RegistroHorario.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:GTS.RegistroHorario.Views"
    Shell.FlyoutBehavior="Disabled">

    <ShellContent
        Title="Home"
        ContentTemplate="{DataTemplate local:MainPageView}"
        Route="MainPageView" />

</Shell>

The code behind of AppShell in AppShell.xaml.cs:

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();



        Routing.RegisterRoute(nameof(ConfiguracionPageView), typeof(ConfiguracionPageView));
    }
}

The MauiProgram.cs

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });



        //Se registran las dependencias.
        builder.Services.AddSingleton<MainPageView>();
        builder.Services.AddSingleton<MainPageViewModel>();

        builder.Services.AddTransient<ConfiguracionPageView>();
        builder.Services.AddTransient<ConfiguracionPageViewModel>();


        return builder.Build();
    }
}

How could navigate to another page if there is an error in the constructor of the main page?

Thanks.

Upvotes: 0

Views: 73

Answers (1)

H.A.H.
H.A.H.

Reputation: 3907

First, and most important thing:

You do not execute code in the constructors of the pages. Especially not code that takes too much time, such as reading DB / Network communications.

You should, let the page construct, and then use Events for example, to run some background work.

You can start by switching all your code to the Appearing event, and work from that point towards something better.

Upvotes: 2

Related Questions