首先将Frame 类型的公共属性添加到您的HomePage:
public Frame NavigationFrame => ContentFrame;
现在,您的 HomePage 当前位于根 Frame 中。要获得它,您必须使用它的 Content 属性:
public class NavigationService : INavigationService
{
public void NavigateTo(Type viewType)
{
var rootFrame = Window.Current.Content as Frame;
var homePage = rootFrame.Content as HomePage;
homePage.NavigationFrame.Navigate(viewType);
}
public void NavigateBack()
{
var rootFrame = Window.Current.Content as Frame;
var homePage = rootFrame.Content as HomePage;
homePage.NavigationFrame.GoBack();
}
}
更简单的解决方案
为了进一步简化这一点,您甚至可以完全删除 rootFrame。在App.xaml.cs 中,您必须更新代码以直接创建HomePage:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
HomePage page = Window.Current.Content as HomePage;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (page == null)
{
page = new HomePage();
Window.Current.Content = page;
}
if (e.PrelaunchActivated == false)
{
// Ensure the current window is active
Window.Current.Activate();
}
}
您现在可以使用以下命令访问NavigationFrame 属性:
public class NavigationService : INavigationService
{
public void NavigateTo(Type viewType)
{
var homePage = Window.Current.Content as HomePage;
homePage.NavigationFrame.Navigate(viewType);
}
public void NavigateBack()
{
var homePage = Window.Current.Content as HomePage;
homePage.NavigationFrame.GoBack();
}
}
现在HomePage 直接是你的Window 的Content,所以我们可以通过Window.Current.Content 访问它。