【问题标题】:Changing MainPage on OnResume event在 OnResume 事件上更改 MainPage
【发布时间】:2019-08-26 19:12:38
【问题描述】:

我正在使用 Xamarin Forms 开发一个小型应用程序,该应用程序需要签名用户,因此 App 构造函数中的 MainPage 设置为 LoginPage。

用户登录后,我将 MainPage 更改为 AppShell,这部分运行顺利,但每次恢复应用程序时,我都需要将用户重定向到 LoginPage。

我的代码如下所示:

App.xaml.cs

public App()
{
  InitializeComponent();

  DependencyService.Register<RestDataStore>();
  DependencyService.Register<CredentialsService>();

  MainPage = new LoginPage();
}

在LoginPage的ViewModel中重定向到AppShell

public void OnSubmit()
{
  ...               
  Application.Current.MainPage = new AppShell(); 
}

App.xaml.cs

protected override void OnResume()
{
  MainPage = new LoginPage();
}

当我像这样更改页面时,什么都不会发生。

有没有其他方法可以在应用程序恢复后更改 MainPage? 我做错了什么?

【问题讨论】:

  • 您是否验证过 OnResume 中的代码正在执行?每次任务切换时都强制用户登录似乎是一个非常糟糕的用户体验设计
  • 为什么还要添加它作为依赖服务?登录与平台无关。
  • 是的,我做到了,事件被正确触发,但 Page 保持与暂停前相同。由于公司严格的安全措施,我们的客户要求这种行为。
  • 不要像那样设置MainPage,只需使用await Navigation.PushAsync (new LoginPage ());
  • 我已将代码从构造函数更改为 MainPage = new NavigationPage(new LoginPage()); ,重定向到 AppShell 到 Application.Current.MainPage.Navigation.PushAsync( new AppShell()); 和 OnResume 到 var nav = MainPage.Navigation; await nav.PushAsync(new LoginPage()); 但 OnResume 重定向不起作用,现在它抛出关于导航的异常在 Android 上,我应该使用 NavigationPage。

标签: c# xamarin.forms xamarin.android


【解决方案1】:

你在你的应用中使用 MasterDetailPage 吗?

如果是这样:

    public static void SetDatailPage(Page page)
    {
        if (App.Current.MainPage is MasterDetailPage)
        {
            var masterPage = (MasterDetailPage)App.Current.MainPage;
            masterPage.Detail = new NavigationPage(page);
        }
    }

    protected override void OnResume()
    {
        // Handle when your app resumes
        SetDatailPage(new LoginPage());
    }

【讨论】:

    【解决方案2】:

    这对我有用:

    protected override async void OnResume()
    {
    
      await MainPage.Navigation.PushModalAsync(new NoConnectionPage());
    
    }
    

    唯一的缺点是它会是模态的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      相关资源
      最近更新 更多