Not able to navigate to pages on Windows Metro App using c#

你。 提交于 2019-12-18 15:04:24

问题


When my UserLogin page loads, i want to check for user database, and if it doesn't exist, or can't be read, i want to direct it to NewUser page.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    CheckForUser();
    if (UserExists == false)
        this.Frame.Navigate(typeof(NewUser));
}

The problem is that it never navigates to NewUser, even when i comment out the if condition.


回答1:


Navigate can't be called directly form OnNavigatedTo method. You should invoke your code through Dispatcher and it will work:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    CheckForUser();
    if (UserExists == false)
        Dispatcher.RunAsync(CoreDispatcherPriority.Normal, 
                            () => this.Frame.Navigate(typeof(NewUser)));
}



回答2:


This happens because your app tries to navigate before the current frame completely loaded. Dispatcher could be a nice solution, but you have to follow the syntax bellow.

using Windows.UI.Core;

    private async void to_navigate()
    {
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.Frame.Navigate(typeof(MainPage)));
    }
  1. Replace MainPage with your desired page name.
  2. Call this to_navigate() function.



回答3:


you can try this and see if this works

frame.Navigate(typeof(myPage)); // the name of your page replace with myPage

full example

    var cntnt = Window.Current.Content;
    var frame = cntnt as Frame;

    if (frame != null)
    { 
        frame.Navigate(typeof(myPage));
    }
    Window.Current.Activate();

or

if you want to use a 3rd party tool like Telerik try this link as well

Classic Windows Forms, Stunning User Interface




回答4:


I see you override OnNavigatedTo method but do not call base method. It may be the source of problem. Try calling base method before any logic:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    CheckForUser();
    if (UserExists == false)
        this.Frame.Navigate(typeof(NewUser));
}



回答5:


Use Dispatcher.RunIdleAsync to postpone your navigation to another page until UserLogin page is completely loaded.




回答6:


The others are correct, but since Dispatcher doesn't work from the view model, here's how to do it there:

SynchronizationContext.Current.Post((o) =>
{
    // navigate here
}, null);


来源:https://stackoverflow.com/questions/13825085/not-able-to-navigate-to-pages-on-windows-metro-app-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!