WinRt page navigation

2019-05-28 16:58发布

How do you navigate to a page from code that is inside of a custom class. For example, lets say I have this code in my MainPage.xaml.cs:

private void DoSomething(object sender, RoutedEventArgs e)
{
   var work = new Work();
   work.doMore();
}

and in this class here is where I would like the navigation to actually take place:

public class Work
{
   public void DoMore()
   {
      // this is what I've tried, but doesn't work
      var myFrame = new Frame();
      myFrame.Navigate(typeof(HomePage));
   }
}

1条回答
The star\"
2楼-- · 2019-05-28 17:22

The code you tried doesn't work because is not the main frame, you should publish the MainFrame reference to the rest of your code so that you can navigate outside views code behind. If you are making something simple I recommend putting a static property on the App class publishing the main frame instance.

EDIT: Some code

On App.xaml.cs
      public static Frame MainFrame{get;private set;}

      protected override void OnLaunched(LaunchActivatedEventArgs args)
            {
                Frame rootFrame = Window.Current.Content as Frame;
                MainFrame = rootFrame;
(....)
            }
Usage:
       App.MainFrame.Navigate(...);
查看更多
登录 后发表回答