xamarin.formsfreshmvvm

How to open a page from App.xaml.cs if not open already


I have a Xaml.Forms app that uses FreshMVVM. I open a certain page from app.xaml.cs like this:

        Xamarin.Forms.Device.BeginInvokeOnMainThread(async () =>
        {
            var navService = FreshIOC.Container.Resolve<IFreshNavigationService>(FreshMvvm.Constants.DefaultNavigationServiceName);
            Page page = FreshPageModelResolver.ResolvePageModel<SomePageModel>();
            await navService.PushPage(page, null);

    ...
        });

But I need to add a check to prevent doing this if this page is already open. How can I make such a check?


Solution

  • Add a static bool value in the App class to check if the page has been opened:

    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);
                });
            }
        }
    }
    

    And in the page's OnDisappearing method, set the isPageOpened to false:

    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    
        protected override void OnDisappearing()
        {
            base.OnDisappearing();
    
            App.isPageOpened = false;
        }
    }