有没有办法判断当前是否显示内容页面?
我需要 ContentPage 中的事件处理程序内的代码来检查页面当前是否显示并采取相应的操作。
除了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;
您可以收听
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 所说的进行操作。
如果您有一个从 Shell 派生的 AppShell 作为您的主页,您可以运行
bool isOnMainPage = Shell.Current.CurrentPage == MyPage