How to change start page at startup?

2019-02-19 09:57发布

my application, currently, goes to the MainPage.xaml at startup (I don't know where it has configured though).

I want to be able to start with another page in some conditions. I think I can add this code to Application_Launching() in App.xaml.cs page:

NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative));

but NavigationService is not available in App.xaml.cs.

How can I start the application with another page if foo == true?

2条回答
萌系小妹纸
2楼-- · 2019-02-19 10:09

Here is a way to navigate depending on a condition:

In the constructor of App.xaml.cs add:

RootFrame.Navigating+= RootFrameOnNavigating;

and then define RootFrameOnNavigating like this:

    private bool firstNavigation = true;
    private void RootFrameOnNavigating(object sender, NavigatingCancelEventArgs navigatingCancelEventArgs)
    {

        //by defaullt stringOfPageNameSetInWMAppManifest is /MainPage.xaml
        if (firstNavigation && navigatingCancelEventArgs.Uri.ToString().Contains(stringOfPageNameSetInWMAppManifest))
        {
            if (foo == true)
            {
                //Cancel navigation to stringOfPageNameSetInWMAppManifest
                navigatingCancelEventArgs.Cancel = true;

                //Use dispatcher to do the navigation after the current navigation has been canceled
                RootFrame.Dispatcher.BeginInvoke(() =>
                {

                    RootFrame.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
                });
            }
        firstNavigation = false;
    }

Another way will be to use a UriMapper to redefine what uri is navigated to when you navigate to a certain page.

查看更多
【Aperson】
3楼-- · 2019-02-19 10:24

Changing start page in App.Xaml.cs:

private void Application_Launching(object sender, LaunchingEventArgs e)
{

        Uri nUri = new Uri("/SecondPage.xaml", UriKind.Relative);
        ((App)Application.Current).RootFrame.Navigate(nUri);

}

Setting static startup page in Property\WMAppManifest.xml file

<DefaultTask  Name ="_default" NavigationPage="SecondPage.xaml"/>

edit

Try it:

    private void Application_Launching(object sender, LaunchingEventArgs e)
    {
        Uri nUri = new Uri("/GamePage.xaml", UriKind.Relative);
        RootFrame.Navigate(nUri);
    }

and in Property\WMAppManifest.xml clear NavigationPage:

<DefaultTask  Name ="_default" NavigationPage=""/>
查看更多
登录 后发表回答