在Xamarin表单中生成BackButton覆盖方法后无法退出应用程序

时间:2017-11-22 07:07:38

标签: c# xamarin xamarin.forms

所以以前我想让我的应用程序在按下Pyshical BackButton后返回MainPage。我已经做到了,但问题是当我在MainPage上并按下Pyhsical Button时,而不是关闭应用程序,它不会去任何地方。第二个问题是当页面堆栈为2(MainPage> News> NewsDetail)时,它直接进入MainPage(DetailNews> MainPage)。我想要做的是弹出previouse Page(DetailNews> News> MainPage>)。这是我的完整代码,用于覆盖后退按钮

  public bool DoBack
        {
            get
            {
                MasterDetailPage mainPage = App.Current.MainPage as MasterDetailPage;

                if (mainPage != null)
                {
                    bool canDoBack = mainPage.Detail.Navigation.NavigationStack.Count > 1 || mainPage.IsPresented;

                    // we are on a top level page and the Master menu is NOT showing
                    if (!canDoBack)
                    {
                        // don't exit the app just show Dashboard
                        //mainPage.IsPresented = true;

                        Type page = typeof(DrawerPage);

                        mainPage.Detail = new NavigationPage((Page)Activator.CreateInstance(page));
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                return true;
            }
        }

我应该添加或更改什么代码来执行此操作,任何消化?

2 个答案:

答案 0 :(得分:1)

第一个问题: 你的逻辑错了。如果你想留在MainPage上,你需要返回true。

  public bool DoBack
        {
            get
            {
                MasterDetailPage mainPage = App.Current.MainPage as MasterDetailPage;

                if (mainPage != null)
                {
                    bool canDoBack = mainPage.Detail.Navigation.NavigationStack.Count > 1 || mainPage.IsPresented;

                    // we are on a top level page and the Master menu is NOT showing
                    if (!canDoBack)
                    {
                        // don't exit the app just show Dashboard
                        //mainPage.IsPresented = true;

                        Type page = typeof(DrawerPage);

                        mainPage.Detail = new NavigationPage((Page)Activator.CreateInstance(page));
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                return true;
            }
        }

第二个问题: 它从DetailsNews直接进入MainPage的原因是你调用PopToRoot而不是Pop。阅读此article

答案 1 :(得分:0)

我已经发现解决方案我在每个详细信息页面中覆盖OnBackButtonPressed

  protected override bool OnBackButtonPressed()
            {
                Device.BeginInvokeOnMainThread(async () => {
                    Application.Current.MainPage = new DrawerPage();
                });

                return true;
            }