user1206480 user1206480 - 3 years ago 43
C# Question

WinRt page navigation

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

DVD DVD
Answer Source

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(...);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download