Search code examples
c#windows-store-appswinrt-xaml

Doing navigation in App.xaml.cs within resume handler


I have a C#/XAML Windows Store App and I need to be able to perform some network/RESTful API tests in the resume handler to make sure that a token/session is still valid. If it isn't, the app needs to direct the user back to the login page.

I've tried a number of solutions on SO and for one reason or another, they won't work from within App.xaml.cs. The overarching issue seems to be my inability to get to Frame.Navigate from within the resume handler.

    public App()
    {
        this.InitializeComponent();
        this.Suspending += OnSuspending;
        Application.Current.Resuming += new EventHandler<object>(OnResuming);
    }

    private async void OnResuming(object sender, object e)
    {
        bool success = true;
        // some tests are performed here
        if (!success) { /* what do I use here? */ }
    }

I've tried solutions on the following pages:


Solution

  • In your example your handling the Resuming event from within your Application class as opposed to somewhere else. You can attach a resuming handler anywhere even within your application pages.

    This example from MSDN (How to resume an app) binds the resume handler directly on the MainPage class where you should have no problem accessing the Frame.Navigate method. You could even create a PageBase class which adds this resume handler automatically so all of your pages can take advantage of this functionality.

    Another solution is to just grab the root frame. The default WinRT sample app uses the following:

    Frame rootFrame = Window.Current.Content as Frame;
    

    So you should be pretty safe doing the same thing. Though you said that you were unable to get to Frame.Navigate for some reason so I'm not user if this is something you've already tried.

    The main thing is to make sure that you're not blocking the UI thread at all. The Resuming event is not called on the UI thread so it won't block it by default but make sure you take advantage of async/await anyway, and use the Dispatcher to update any of the UI.