导航服务对象实例错误
本文关键字:错误 实例 对象 服务 导航 | 更新日期: 2023-09-27 18:12:49
我是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));
}
在Page中使用NavigationService实例。阅读MSDN关于导航的文章
private void CloseApplication_MouseUp(object sender, MouseButtonEventArgs e)
{
this.NavigationService.Navigate(new Uri ("Page1.xaml", UriKind.Relative));
}
应该非常简单。导航发生在NavigationWindowPages中的,参见下面的示例:
首先,你的主窗口应该继承自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);
}