2

我对 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.

你能帮我吗?

4

1 回答 1

4

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

但是对于导航,您需要一个页面MSDN 上的导航概述

一个小工作示例:

创建到Page的Page1.xaml、Page2.xaml

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

第 1 页 Xaml:

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

第 1 页 CS:

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

第2页Xaml:

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

第2页cs:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        NavigationService nav = NavigationService.GetNavigationService(this);
        nav.Navigate(new Uri("Page1.xaml", UriKind.RelativeOrAbsolute));
    }
于 2014-08-11T09:05:36.000 回答