检查ContentPage当前是否显示

问题描述 投票:0回答:4

有没有办法判断当前是否显示内容页面?

我需要 ContentPage 中的事件处理程序内的代码来检查页面当前是否显示并采取相应的操作。

c# xamarin xamarin.forms
4个回答
5
投票

除了GBreen12的答案之外,你还可以这样做......

bool isShowingMyPage = Application.Current.MainPage is MyPage || (Application.Current.MainPage is NavigationPage navPage && navPage.CurrentPage is MyPage); //If you are using a MasterDetailPage or something else, then you would have to handle this differently

//I think the below will work for checking if any modals are showing over your page but you should definitely test it in different scenarios to make sure. I am not sure if the modal is immediately removed from ModalStack when it gets popped or not

isShowingMyPage = Application.Current.MainPage?.Navigation?.ModalStack?.LastOrDefault() == null;

2
投票

您可以覆盖

OnAppearing
,它会在页面即将显示时调用:

xamarin.forms 中的页面生命周期事件


1
投票

您可以收听

NavigationPage
Pushed
Popped
事件,如下所示:

((Xamarin.Forms.NavigationPage)MyProject.App.Current.MainPage).Pushed += (s, e) => 
{
    if (e.Page is ContentPage)
    {
        // Do what you gotta do
    }

    // or, for a specific page:
    if (e.Page is MyProject.Views.MyCustomPage)
    {
        // Do what you gotta do
    }
};

当然,只有当页面被推送到导航堆栈时才会调用此方法;如果您需要每次页面出现在屏幕上时都调用它,请按照 GBreen12 或 hvaughan3 所说的进行操作。


0
投票

如果您有一个从 Shell 派生的 AppShell 作为您的主页,您可以运行

  bool isOnMainPage = Shell.Current.CurrentPage == MyPage
© www.soinside.com 2019 - 2024. All rights reserved.