问题 无法使用c#导航到Windows Metro App上的页面


当我的 UserLogin 页面加载,我想检查用户数据库,如果它不存在,或无法读取,我想指向它 NewUser 页。

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

问题是它永远不会导航到 NewUser,即使我评论出来了 if 条件。


11174
2017-12-11 17:11


起源

你检查MSDN **这里是一个链接 msdn.microsoft.com/en-us/library/windows/apps/br211386.aspx ** - MethodMan
我不认为你可以导航 OnNavigatedTo 方法,因为你仍然在导航的中间。 - Trisped


答案:


Navigate 不能直接调用形式 OnNavigatedTo 方法。你应该通过调用你的代码 Dispatcher 它会起作用:

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

14
2017-12-12 05:40



请务必在覆盖方法调用的顶部调用base.OnNavigatedTo(e)。我有相同的代码,减去base.OnNavigatedTo(e),我仍然得到一个例外。这个答案帮助了我,谢谢! - Allen Rufolo


发生这种情况是因为您的应用尝试在当前帧完全加载之前导航。 Dispatcher可能是一个很好的解决方案,但您必须遵循下面的语法。

使用Windows.UI.Core;

    private async void to_navigate()
    {
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.Frame.Navigate(typeof(MainPage)));
    }
  1. 用您想要的页面名称替换MainPage。
  2. 将此命名为to_navigate()函数。

1
2017-10-04 13:06





你可以尝试这个,看看这是否有效

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

完整的例子

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

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

要么

如果你想使用像Telerik这样的第三方工具,也可以尝试这个链接

经典的Windows窗体,令人惊叹的用户界面


0
2017-12-11 17:15





我看到你重写OnNavigatedTo方法但不调用基本方法。它可能是问题的根源。 尝试在任何逻辑之前调用base方法:

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

0
2017-12-12 02:24





使用Dispatcher.RunIdleAsync将导航推迟到另一个页面,直到完全加载UserLogin页面。


0
2017-12-13 16:03





其他是正确的,但由于Dispatcher不能从视图模型中工作,所以这里是如何做到的:

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

0
2018-05-19 01:54