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

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

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

问题是它永远不会导航到NewUser ,即使我注释掉if条件。

无法直接从OnNavigatedTo方法调用Navigate 。 您应该通过Dispatcher调用您的代码,它将工作:

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

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

使用Windows.UI.Core;

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

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

 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窗体,令人惊叹的用户界面

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

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

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

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

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