Exit application on “Back” button on WP7

家住魔仙堡 提交于 2019-12-01 05:43:45

This is a fairly common scenario with either doing a one-off task on 1st time run of an app, or if you need to login to use the app at all. Rather than writing this as a full page I'd recommend putting a UserControl in a full-screen Popup over your main page. That way a single Back key press will always exit your app.

You may want to restructure your application. Do not have a MainPage at all, always load PageA. If the user hasn't set preferences, just redirect them to PageB, they'll set preferences and hit the Back button which takes them back to PageA. Since the app now has the settings it needs it can display PageA normally.

If you really must use the 3 page scheme, you may be able to get the NonLinear Navigation Service to work its magic.

You could achieve this goal by e.g. having a static boolean variable on the App class, e.g. ForceExitApplication and set this to true on Page_A or Page_B. On MainPage you would check this variable and if its set to true you exit the application:

  • Either by calling NavigationService.GoBack() (I think this would work)
  • Or by throwing an exception (this would work, but will definitely fail marketplace submission)

I would, however be vary of implementing this behaviour. It seems that what you are trying to achieve - exiting the application at a point other than the main page - is against the WP7 guidelines and if this is so, your application is likely to get rejected when submitting until you fix this issue.

In Mango you could use the following approach:

in app.cs add event handler to RootFrame.Navigated event:

 RootFrame.Navigated += RootFrame_Navigated;

Then within the event handler, we could utilize the navigation backstack:

void RootFrame_Navigated(object sender, NavigationEventArgs e)
{
    var pageBURI = "/Pages/Page_B.xaml";
    var pageAURI = "/Pages/Page_A.xaml";

    if ((e.Uri == pageAURI || e.Uri == pageBURI) && RootFrame.BackStack.Count() > 0)
    {
        RootFrame.RemoveBackEntry();
    }
}

What does this code do: First, we are checking, if we have navigated to page A or B. Then we are checking, if we have any pages in navigation backstack. (It should be at least one, because, we had already been redirected from mainPage). Then, we are removing the last entry from the backstack journal. Now, of a user will press the "Back" button, the application will exit.

You could read more about BackStack here: http://msdn.microsoft.com/en-us/library/hh394012(v=vs.92).aspx

The root item in the visual tree of most pages is a grid. It is trivial to organise your two UIs into two grids hosted by a stackpanel and bind the visibility of each to a page dependency property so that this property controls which is visible. There is no reason a single page can't serve both purposes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!