MAUI Programmatically set Start/Root page

Dino 65 Reputation points
2023-03-15T07:25:11.9166667+00:00

Hi everybody.
.net 7, VS 2022 latest, default maui application, mvvm toolkit, an half cup of coffee remaining.
I am porting, as a POC, an Android Application to MAUI.
I can successufully parse the deep link, and extract 'appmode' variable, storing it in a global variable. Url is a kind of myapp://.... &appmode=A&...

In the Android code, if appmode is A or B I inflate the correct Fragment and works flawlessy.

In MAUI I can in the App.cs constructor switch and set MainPage

  switch (Globals.AppMode)
        {
            case AppModeEnum.A:
                MainPage = new NavigationPage(new APage());
                break;

.... however this happens Before I parse querystring/deeplink in Platform/Android/MainActivity/OnCreate, so Globals.Appmode is not correctly set... yet.
Playing with AppShell (and using a different approach), for unknown reason, I loose the navigation and my pop/push async are ignored. I know I have to write the code, to explain but I will keep this post shorter.

Navigation is done with Mvvm (coomunity toolkit) messaging because of my experience in WPF, so the (root) View (PageA or PageB) registers and captures the message and navigate to correct View, populating the BindingContext received from NavigateToMessage parameter.

In PageA.cs code behind

 WeakReferenceMessenger.Default.Register<NavigateToMessage>(this, async (s, e) =>
 {
            DocumentPage d = new();
            d.BindingContext = e.ViewModel;
            await Navigation.PushAsync(d);
  });

So, sorry for the long description, is there a way to set the start/root page in my app, after deeplink is processed, and preserve the navigation functions?
Just for be complete, if app starts in mode A it has own Pages ad views and never "switch" in mode B, or viceversa. if PageA is root it will be for all app lifecycle.

Many thanks

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,231 questions
{count} votes

Accepted answer
  1. Alessandro Caliaro 4,181 Reputation points
    2023-03-15T10:58:43.6133333+00:00

    Yes,

    [0:] MauiApp: MauiApp

    [0:] App: App

    [0:] AppShell: AppShell

    [0:] MainActivity: OnCreate

    this seems to be the execution flow.

    Maybe you can move the switch inside the MainActivity?

    Like this:

        protected override void OnCreate(Bundle savedInstanceState)
        {
    
            App.Current.MainPage = new AppShell();
    
            base.OnCreate(savedInstanceState);
    
        }
    

0 additional answers

Sort by: Most helpful