【问题标题】:Not able to navigate to pages on Windows Metro App using c#无法使用 c# 导航到 Windows Metro App 上的页面
【发布时间】:2012-11-29 06:59:01
【问题描述】:

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

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

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

【问题讨论】:

标签: c# navigation microsoft-metro windows-runtime


【解决方案1】:

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)));
}

【讨论】:

  • 确保在覆盖方法调用的顶部调用 base.OnNavigatedTo(e)。我有同样的代码,减去 base.OnNavigatedTo(e) 并且我仍然遇到异常。这个答案帮助了我,谢谢!
【解决方案2】:

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

使用 Windows.UI.Core;

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

【讨论】:

    【解决方案3】:

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

    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 之类的第 3 方工具,也可以试试这个链接

    Classic Windows Forms, Stunning User Interface

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-12-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多