Using URI mappers on Windows Phone

Posted on Aug 7, 2014 | Categories: coding, windowsphone


There are many possibilities to redirect your users to the right location in your Windows Phone app. One of the most used options being used is by calling NavigationService.Navigate(...); on the MainPageLoaded event in the MainPage.xaml file. But hey, there’s something better:

I dislike this method because changes are big you execute all your initialization logic in the MainPage.xaml file. A much seen use case in my applications is that there is the need of authenticating users. If the user is already authenticated you want them to directly go to the MainPage. If they’re not yet authenticated you want them to go to the LoginPage and maybe execute some specific login logic there. Hey, good news! There’s something which may help you and it’s called the UriMapper.

var mapper = new UriMapper();
if (!String.IsNullOrEmpty(settings["accessToken"].ToString()))
{
    mapper.UriMappings.Add(new UriMapping
    {
        Uri = new Uri("/Initialize.xaml", UriKind.Relative),
        MappedUri = new Uri("/Views/MainPage.xaml", UriKind.Relative)
    });
}
else
{
    mapper.UriMappings.Add(new UriMapping
    {
        Uri = new Uri("/Initialize.xaml", UriKind.Relative),
        MappedUri = new Uri("/Views/LoginPage.xaml", UriKind.Relative)
    });
}

RootFrame.UriMapper = mapper;

This simple code I’ve added in one of my applications checks if the accessToken contains some usable value. If that statement is true it’ll direct you to the MainPage. If it evaluates to false it’ll redirect you to the LoginPage. One of the interesting things you’ll see is that I’m mapping Initialize.xaml. Please note that Initialize.xaml doesn’t exits anywhere in my project. The only thing I did was adding it to WMAppManifest.xml page as the Navigation Page.

If you want to implement this in your own regular Windows Phone application you have to add this code to the CompleteInitializePhoneApplication function in the App.xaml.cs file. Or, at least you have to add the mapper to the UriMapper here because this function executes when navigation to the RootFrame completed. Please ignore the following comment

// Do not add any additional code to this method

It probably won’t hurt you or your application.

If you’re an Caliburn Micro user then you can add this code to your bootstrapper in the Configure() function. FYI