How to navigate to a xaml page from class

十年热恋 提交于 2019-12-13 04:03:30

问题


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

回答1:


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



回答2:


Use RootFrame in App.xaml

(App.Current as App).RootFrame.Navigate(new Uri("/Page1.xaml", UriKind.RelativeOrAbsolute));


来源:https://stackoverflow.com/questions/19422310/how-to-navigate-to-a-xaml-page-from-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!