在 Template10 中为自定义 Shell 创建 NavigationService

Creating NavigationService for custom Shell in Template10

我正在将现有的 UWP 应用移植到 Template10。该应用程序将汉堡菜单作为自定义 shell 实现,它具有本机 Template10 汉堡菜单模板的所有功能,但还有很多特定于我的应用程序的功能,因此我不想使用提供的模板由图书馆继续使用现有的 shell.

在 shell 中有一个名为 ContentFrameFrame 对象,它应该处理所有页面导航。我需要以某种方式为框架获取一个 INavigationService 对象。经过一番尝试(我没有找到任何关于使用自定义 shells 和 NavigationService 的综合文档)我让它工作了,但我不完全确定为什么:

public override UIElement CreateRootElement(IActivatedEventArgs e)
{            
     _shell = new Shell();
      NavigationServiceFactory(BackButton.Attach, ExistingContent.Exclude, _shell.ContentFrame);
      return new ModalDialog
      {
          Content = _shell
      };
}

public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
     var navService = _shell.ContentFrame.GetNavigationService();
     navService?.NavigateAsync(typeof(TestPage));
}

如果我省略 NavigationServiceFactory() 的调用,代码将无法运行。那么,是否应该在创建需要 NavigationService 的 Frame 时调用它?工厂是否创建某种稍后可以使用 GetNavigationService() 定位的全局 NavigationService。尽管我的代码似乎有效,但我希望在继续之前确认这一点。

是的,你的做法是正确的。正如 documentation 所述:

Template 10 relies on every XAML frame control to have a companion Template 10 navigation service

所以每个应该允许导航的 Frame 都应该创建一个导航服务。

一旦为给定框架创建了导航服务,它就会被注册,然后 GetNavigationService 扩展方法会通过实例检索它(请参阅 source code)。