Maui Blazor Set Startup Page on Open

769 Views Asked by At

Seems a simple enough task, but I'm stymied:

I want to direct the startup page of the app based on a LocalStorage setting.

I'm able to get (and set) LocalStorage without problem, but can't seem to find how to redirect.

app.xaml.cs does the usual:

public App()
{
    InitializeComponent();

    MainPage = new MainPage();
}

and MainPage.xaml.cs:

public MainPage()
{
    InitializeComponent();

    // set redirection page here
    var navPage = GetLocalStorageValue(key: "startupPage", default: "/");
}

Thanks in advance!

2

There are 2 best solutions below

0
Guangyu Bai - MSFT On

You can use the Command to make the redirect. You can use the Command to pass the CommandParameter to the code behind then you can navigate to the page you want.

Code in the MainPage.xaml.cs:

public partial class MainPage : ContentPage
{
    public ICommand NavigateCommand { get; private set; }

    public MainPage()
    {
        InitializeComponent();

        NavigateCommand = new Command<Type>(
            async (Type pageType) =>
            {
                Page page = (Page)Activator.CreateInstance(pageType);
                await Navigation.PushAsync(page);
            });

        BindingContext = this;
    }
}

Code in the MainPage.xaml:

<TextCell Text="Customimze an Entry"
          Detail="Select text on focus"
          Command="{Binding NavigateCommand}"
          CommandParameter="{x:Type views:CustomizeEntryPage}" />
0
Bisjob On

Create a StorageSettingsRedirect.razor component whithout any html content. Add it to your MainLayout.

@inject NavigationManager nav
@inject MyStorageService storageService

@code {
     protected override Task OnInitializedAsync()
    {
        if (await storageService.NeedGoTosetting())
            nav.NavigateTo("/storageSettingsRoute");
        return base.OnInitializedAsync();
    }

When the MainLayout will be displayed, it will render this component. So it will initialize only once at your program startup (unless you changes your mainLayout, in that case I would recommend using one MainLayout and nestedLayouts). Then when your StorageSettingsRedirect component will be initilized, it will check if it needs to redirect to the setting page, and use the navigationManager to change the route