Xamarin.Forms.Application.Current.MainPage 为 null

Dan*_*kin 5 prism xamarin.ios application-lifecycle xamarin.forms

我有将应用程序从 iOS 迁移到 Forms 的异常情况。

我的设置是 -

  1. iOS 项目加载签名 UIViewController 和处理登录例程。MainPage 为空。

  2. 登录例程完成后,我将 XF 视图加载为 UIViewController 并将其添加到导航堆栈

var formsController = formsPage.CreateViewController();

CoreApplication.Instance.FormsController = formsController;

var CurrentNavigationController = UIApplication.SharedApplication.KeyWindow.RootViewController;

var viewControllersStack = CurrentNavigationController.ChildViewControllers;

viewControllersStack[viewControllersStack.Length - 1].NavigationController.PushViewController(CoreApplication.Instance.FormsController, true);
Run Code Online (Sandbox Code Playgroud)

那就是当 MainPage 具有值作为 Navigation 将其设置为导航页面时。

  1. 我转到后台。
protected override void OnSleep()
{
    if (Application.Current.MainPage != null)
    {
        Console.WriteLine("!!!! ---  " + Application.Current.MainPage.GetType().Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在获取 MainPage 的名称 - 所以值不为空。

  1. 我回到前台 => OnResume() 发现 MainPage 为空。

但我又回到了我的 XF 视图。导航在页面之间工作,一切似乎都很好。

现在唯一的问题是 MainPage 现在为 null - 一些库,如 Rg.Plugins.Popup 无法工作,因为它们引用了 MainPage 并且我崩溃了。

关于如何保持 MainPage 引用的任何帮助/想法?

谢谢你!

聚苯乙烯

如果我调用 NavigationService.NavigateAsync(MyPage); 我做了一些调查;从 App.xaml.cs 或 do=> MainPage = new MyPage(); 然后 MainPage 的实例在所有应用程序生命周期中保持活动状态。

Dan*_*kin 2

从原始帖子的评论中可以看出 - 问题的解决方案是当 XF 成为应用程序启动时的第一响应者时移动应用程序逻辑。然后我正常管理导航,并在需要加载 UIViecontrollers 时 - 将 UIApplication.SharedApplication.KeyWindow 获取到 Present ViewController。

有关如何执行此操作的更多详细信息,请参阅此处