Xamarin.Forms应用恢复时还原导航堆栈

时间:2019-04-26 15:58:44

标签: xamarin xamarin.forms navigation state-management

我正在构建具有以下页面的应用程序,依次为:

(P)ContentPage
(V)ContentView托管在ContentPage上。
->:正在执行的调用或代码。

(P) Main
   -> If login not detected, automatically goes to:
       (P) Startup
           (P) Sign up, has these ContentViews as registration steps:
               (V) Email and password
               (V) Name
               (V) Profile photo
                   -> Call to CrossMedia.Current.TakePhotoAsync
               (V) Other details
                   -> Returns to Main, if has successful profile creation.
           (P) Sign in
               -> Returns to Main, if has successful login.
   -> If login detected:
        -> Load the content of the Main page.

因此,每当我锁定应用程序的屏幕或切换应用程序(例如通过调用CrossMedia插件打开相机)时,该应用程序都会再次直接进入“主页”,从而将用户引导回“启动”页面,如果没有检测到登录名。

有什么办法可以解决这个问题?怎么样? 是否应将导航堆栈保存在OnSleep方法的某个位置? 每个页面的DataContext呢?如何保存它们?

有什么办法可以阻止这种情况的发生?

2 个答案:

答案 0 :(得分:0)

您可以在应用程序进入睡眠模式或contentPage消失时设置应用程序级别属性。如果属实,则可以跳过登录签入的恢复方法,让用户在它离开的地方恢复该应用程序。

在App.xaml.cs中

public static bool IsSignUpInProgress{get;set;}

protected override void OnSleep()
        {
            if(Application.Current.MainPage==typeof(SignUpPage))
                IsSignUpInProgress=true;
        }
protected override void OnResume()
    {
        if(IsSignUpInProgress==false)
            {
                //Do your login check.
             }
    }

答案 1 :(得分:0)

好的,我可以通过在MainPage启动方法上添加断点来检测到问题。

基本上,我要做的是通过使用简单的bool变量(_loaded)检查页面是否已加载。

    protected override async void OnAppearing()
    {
        base.OnAppearing();

        IsBusy = true;

        if (!_loaded && !await ViewModel.Auth.IsLoggedIn())
        {
            _loaded = true;
            await App.NavigationHelper.NavigateModalAsync(new Startup(), false);
        }

        IsBusy = false;
    }

应用恢复后,即使在切换应用(例如相机)时,MainPage仍在执行OnAppearing方法。

App.xaml.cs构造函数外,没有其他对该页面的调用,因此框架必须在调用它,因为它是应用程序的主页。