如果尚未打开,如何从 App.xaml.cs 打开页面

问题描述

我有一个使用 FreshMVVM 的 Xaml.Forms 应用程序。我像这样从 app.xaml.cs 打开某个页面

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
     db.collection("users").doc(user.uid).get()
     .then(snap => {
        localStorage.setItem('userData',JSON.stringify(snap.data()));
     });
  } else {
    // No user is signed in.
  }
});

但是如果此页面已经打开,我需要添加一个检查以防止这样做。我怎样才能进行这样的检查?

解决方法

在App类中添加一个静态bool值来检查页面是否已经打开:

public partial class App : Application
{
    public static bool isPageOpened;
    public App()
    {
        InitializeComponent();

        MainPage = new MainPage();
    }

    public void test()
    {

        if (App.isPageOpened = false)
        {
            Xamarin.Forms.Device.BeginInvokeOnMainThread(async () =>
            {
                var navService = FreshIOC.Container.Resolve<IFreshNavigationService>(FreshMvvm.Constants.DefaultNavigationServiceName);
                Page page = FreshPageModelResolver.ResolvePageModel<SomePageModel>();

                App.isPageOpened = true;

                await navService.PushPage(page,null);
            });
        }
    }
}

在页面的 OnDisappearing 方法中,将 isPageOpened 设置为 false:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();

        App.isPageOpened = false;
    }
}