您可以使用导航窗口的 CurrentSource 属性在后面的代码中获取当前正在运行的页面。根据您的要求,使用 NavigationService.Navigate() 方法完成,如下所示:
导航窗口.xaml:
<NavigationWindow x:Class="WPFTest.MyNavWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="768" Width="1024" Source="ShopList.xaml" Grid.Row="1"
WindowState="Maximized" ResizeMode="NoResize" ShowsNavigationUI="True" WindowStyle="SingleBorderWindow" Cursor="Arrow" Navigated="NavigationWindow_Navigated">
</NavigationWindow>
导航窗口.xaml.cs:
namespace WPFTest
{
public partial class MyNavWindow : NavigationWindow
{
public MyNavWindow()
{
InitializeComponent();
}
private void NavigationWindow_Navigated(object sender, NavigationEventArgs e)
{
MessageBox.Show(((NavigationWindow)this).CurrentSource.ToString());
}
}
}
ShopList.xaml:
<Page x:Class="WPFTest.ShopList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ShopList">
<Grid>
<Label Height="28" Margin="81,12,99,0" Name="label1" VerticalAlignment="Top" FontSize="16" FontWeight="Bold">Shop List</Label>
<Button Name="btnNext" Content="Go to Product list" Width="150" Height="30" Margin="0,50,0,0" Click="btnNext_Click"></Button>
</Grid>
ShopList.xaml.cs:
namespace WPFTest
{
public partial class ShopList : Page
{
public ShopList()
{
InitializeComponent();
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new System.Uri("ProductList.xaml", UriKind.Relative));
}
}
}
产品列表.xaml:
<Page x:Class="WPFTest.ProductList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ProductList">
<Grid>
<Label Height="28" Margin="81,12,99,0" Name="label1" VerticalAlignment="Top" FontSize="16" FontWeight="Bold">Product List</Label>
</Grid>
</Page>
它对我来说很好。希望这能解决您的问题。请随时询问是否无法解决。
更新 :
如果您想使用类名而不是 Uri 来导航页面,那么您可以获得当前源,例如:
MessageBox.Show(((NavigationWindow)this).NavigationService.Content.GetType().Name.ToString() + ".xaml");