How to navigate to a xaml page from class

2019-08-25 04:36发布

In my application, I have a class Chronometer which use a dispatcherTimer and Tick method. Each second, a variable decrease.

I would like that when the value of the variable is 0, a new xaml page is load.

I try to use NavigationService but this method work only in a xaml.cs file.

My xaml page which is visible when the variable decrease is : WordPage.xaml The xaml page that i want to display is : FinalPage.xaml

Can you realize what I want? Please help me

EDIT :

My constructor of my class is :

public Chrono(DispatcherTimer newTimer, TextBlock chrono, TextBlock NumEquip, P1 page1)
    {
     //Part effaced
     m_page1 = page1;
    }

and the instanciation of the object Chrono is :

MonChrono = new Chrono(newTimer, this.TimeLabel,  this);

2条回答
Anthone
2楼-- · 2019-08-25 05:21

Use RootFrame in App.xaml

(App.Current as App).RootFrame.Navigate(new Uri("/Page1.xaml", UriKind.RelativeOrAbsolute));
查看更多
甜甜的少女心
3楼-- · 2019-08-25 05:27

You cannot create an instance of NavigationService, that's the main problem. But you could possibly pass your page object as a parameter and access its NavigationService.Property

public void NavigateToPage(YouPageClass page)
{
    page.NavigationService.Navigate(new Uri("/Pages/PageToNavigateTo.xaml",
        UriKind.RelativeOrAbsolute));
}

Sample project: http://www.abouchleih.com/wp-content/uploads/TestNavigationFromClass.zip

Edit: I found a better solution. Don't pass the page object, bette pass it's NavigationService-Property, now you can simply call the same method from multiple pages.

Method in your class:

public static void Nav(NavigationService s, Uri destination)
{
    s.Navigate(destination);
}

Call from a page:

private void button_navigateTo_Click(object sender, RoutedEventArgs e)
{
    NavService.Nav(this.NavigationService, new Uri("/PageToNavigateTo.xaml", UriKind.RelativeOrAbsolute));
}
查看更多
登录 后发表回答