WPF:导航服务对象实例错误

时间:2014-07-14 03:34:20

标签: c# wpf

我是WPF的新手并试图寻找并尝试不同的解决方案: 我需要导航到另一个页面:从名为MainFrame的页面到Page1

错误讯息:

WPF does not containt a definition for navigation service.

或者

Object not set to instance of Object.

我试过了:

    private void CloseApplication_MouseUp(object sender, MouseButtonEventArgs e)
    {
        navService = NavigationService.GetNavigationService(this);
        navService.Navigate(new Uri ("Page1.xaml", UriKind.Relative));
    }

然后我尝试了这个,想想在页面加载时需要实例化的东西:

    NavigationService navService;

    public MainFrame()
    {
        InitializeComponent();
    }

    void MainFrame_Loaded(object sender, RoutedEventArgs e)
    {
        navService = NavigationService.GetNavigationService(this);
    }

    private void CloseApplication_MouseUp(object sender, MouseButtonEventArgs e)
    {
        navService.Navigate(new Uri ("Page1.xaml", UriKind.Relative));
    }

2 个答案:

答案 0 :(得分:0)

在Page中使用NavigationService实例。阅读有关导航的MSDN文章

private void CloseApplication_MouseUp(object sender, MouseButtonEventArgs e)
    {
        this.NavigationService.Navigate(new Uri ("Page1.xaml", UriKind.Relative));
    }

答案 1 :(得分:0)

应该很简单。导航发生在 NavigationWindow 页面中,请参阅下面的示例:

首先,您的主窗口应该继承自 NavigationWindow 类:

public partial class MainWindow : NavigationWindow
{
   public MainWindow()
   {
       InitializeComponent();
   }
}

然后xaml必须有 NavigationWindow 根元素:

<NavigationWindow x:Class="NavigationApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window" Height="300" Width="300" Source="MainPage.xaml">

</NavigationWindow>

此根元素不能包含任何UI元素,因为它们放在页面中。根元素包含起始页面属性MainPage.xaml

<Page x:Class="NavigationApp.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    Title="MainPage">

    <Grid>
        <Frame Source="Page2.xaml"/>
    </Grid>
</Page>

在我的情况下,它包含一个只有一个按钮的Page2.xaml框架。

<Page x:Class="NavigationApp.Page2"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    Title="Page2">

    <Grid>
        <Button Content="Navigate to page 1" HorizontalAlignment="Left" Margin="109,143,0,0" VerticalAlignment="Top" Width="128" Click="Button_Click"/>

    </Grid>
</Page>

点击该按钮,导航到另一个页面:

 private void Button_Click(object sender, RoutedEventArgs e)
 {
    Uri uri = new Uri("Page1.xaml", UriKind.Relative);
    NavigationService.Navigate(uri);
 }