【问题标题】:Check if ContentPage is currently shown检查当前是否显示 ContentPage
【发布时间】:2018-02-05 18:59:08
【问题描述】:

有没有办法判断 ContentPage 当前是否显示?

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

【问题讨论】:

  • 注册事件处理程序 OnAppearing 并在 Disappearing 删除,那么您不必担心它。如果您使用 IPC 的事件处理程序,您将会遇到麻烦,并且可能需要重构一些东西。

标签: c# xamarin xamarin.forms


【解决方案1】:

除了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;

【讨论】:

  • 如果此页面已通过MainPage“推送”或“推送模式”怎么办?
  • @ispiro 如果新页面被“推送”到MyPage 上,那么Application.Current.MainPage 将保留新页面,而不是MyPage。如果您还需要担心模式是否显示在您的 MyPage 上,请查看我的编辑。
【解决方案2】:

您可以覆盖在页面即将显示的任何时候调用的OnAppearing

Page lifecycle events in xamarin.forms

【讨论】:

  • 谢谢。我想到了这一点,并保持了一个布尔标志。但我想知道是否有任何内置方式。
  • 问题出现在 droid 上,它在页面显示之前触发,而在 ios 上,它在页面显示后触发..
【解决方案3】:

您可以收听NavigationPagePushedPopped 事件,如下所示:

((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 所说的进行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    相关资源
    最近更新 更多