从第一篇开始我们就看到了页面的导航切换,上一篇文章则介绍了框架实现导航的原理和过程。真正的导航功能是NavigationService类来实现的。而Frame是Page的载体,是负责导航,历史记录等功能的,相当于一个指挥官。这一篇就主要介绍一下导航的操作和相关的一些方法。

 

一 导航时发生错误

 

 

默认的我们建立一个Windows Phone程序,使用导航功能是不会出现这个问题的。我们先看一个列子:

private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
   // Set the root visual to allow the application to render
   if (RootVisual != RootFrame)
       //RootVisual = RootFrame;
       RootVisual = new MainPage();
    // Remove this handler since it is no longer needed
    RootFrame.Navigated -= CompleteInitializePhoneApplication;
}

我们新建一个项目后,不把Frame设置到RootVsual,而是用MainPage。我们从Mainpage导航到Page1. 使用两种方法:

private void Button_Click(object sender, RoutedEventArgs e)
{
     方法1:this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
     方法2:(Application.Current as App).RootFrame.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}

第一种方法是使用Page页面的NavigationSevice属性来导航,第二种方法是使用Frame对象来导航。从上一篇我们知道,两种方法是相同的。结果是使用第一种方法发生了NullReferenceException错误,为什么NavigationService对象是空?我们不是在App构造函数中就创建过NavigationServie对象的实例吗,并且在加载了XAML文件后设置到了依赖属性中。

继续阅读