3

I have a Xamarin Forms Application where I'm setting the MainPage to NavigationPage during OnStart.
The NavigationPage is static (kept in memory for reuse).
When I press the back button in Android and go back to the app the OnStart method is executed again and the application displays a blank screen.

See the repro here: Xamarin.Forms OnStart Navigation

public partial class App : Application
{
    private static readonly NavigationPage NavigationPage = new NavigationPage(new MainPage());
    public App ()
    {
        InitializeComponent();
    }

    protected override void OnStart()
    {
        MainPage = NavigationPage;
    }
}

If I do the same action in the constructor the application behaves as expected: there's no blank screen and the last page visited is displayed.

See the repro here: Xamarin.Forms Constructor Navigation

public partial class App : Application
{
    private static readonly NavigationPage NavigationPage = new NavigationPage(new MainPage());
    public App ()
    {
        InitializeComponent();

        MainPage = NavigationPage;
    }
}

What is the difference between setting the MainPage in the constructor and in the OnStart method?

4

1 回答 1

3

You do not do it in onstart with static mainpage intialized outside the init call.

Do it in constructor after the InitializeComponents.

Like so:

public partial class App : Application
{
private static readonly NavigationPage NavigationPage;
public App ()
{
    InitializeComponent(); 
    NavigationPage = new NavigationPage(new MainPage());

    MainPage = NavigationPage;
}
}
于 2018-05-30T16:27:58.563 回答