NavigationService.Navigate错误

时间:2014-08-11 07:16:30

标签: c# navigationservice

我对C#编程很新,我的代码有问题。 我创建了一个按钮并在其上应用了一个事件点击,它通过技术NavigationService打开了我项目的另一个页面。

这是剧本:

private void click_login(object sender, RoutedEventArgs e)
{
    NavigationService nav = NavigationService.GetNavigationService(this); 
    nav.Navigate(new Uri("Window1.xaml", UriKind.RelativeOrAbsolute));
}

当我执行时,我收到此错误:

The object reference is not set to an instance of an object with an InnerException null.

你能帮我吗?

1 个答案:

答案 0 :(得分:2)

您的导航对象为空,因为您正在尝试获取WPF窗口的NavigationService。

但是对于导航,您需要PageNavigation Overview on MSDN

一个小小的工作示例:

创建页面的Page1.xaml,Page2.xaml

在App.xaml中更改 StartupUriStartupUri="Page1.xaml"

Page1 Xaml:

 <StackPanel>
     <TextBlock Text="Hello from  Page1" />
     <Button Click="Button_Click" Content="Navigate to page 2"></Button>
 </StackPanel>

Page1 cs:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        NavigationService nav = NavigationService.GetNavigationService(this);
        nav.Navigate(new Uri("Page2.xaml", UriKind.RelativeOrAbsolute));
    }

Page 2 Xaml:

 <StackPanel>
     <TextBlock Text="Hello from  Page2" />
     <Button Click="Button_Click" Content="Navigate to page 1"></Button>
 </StackPanel>

Page2 cs:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        NavigationService nav = NavigationService.GetNavigationService(this);
        nav.Navigate(new Uri("Page1.xaml", UriKind.RelativeOrAbsolute));
    }