Using Uri Fragments with Windows Phone 7 instead of QueryString

There are a number of posts out there (such as this one) talking about the use of QueryString parameters as a way of passing information between pages in a Windows Phone 7 application. An alternative to this is the use of Uri Fragments.

I’ll take Rongchaua’s example as a starting point. Here you can see the code on both the source and destination pages.

// On source page
NavigationService.Navigate(new Uri("/BrowsePage.xaml?RSSSource="+strSource, UriKind.Relative));

// On destination page
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    try
    {
        …
            string strRSSSource = "";
            NavigationContext.QueryString.TryGetValue("RSSSource", out strRSSSource);
        …
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Before we go on to look at using fragments instead of the query string, I’ll make one comment about this code sample. Here Rongchaua has handled the Loaded event of the page. If you want to load data you can actually override the OnNavigatedTo method which will get invoked earlier in the navigation pipeline. You do need to be careful though as the UI may not have been completely loaded at that point.

Coming back to using a uri fragment. Here is the same example, this time using a fragment instead of a QueryString.

// On source page
NavigationService.Navigate(new Uri("/BrowsePage.xaml#"+strSource, UriKind.Relative));

// On destination page
protected override void OnFragmentNavigation(System.Windows.Navigation.FragmentNavigationEventArgs e)
{
    try
    {
        …
            string strRSSSource = e.Fragment;
        …
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

The OnFragmentNavigation method gets invoked after the page has been navigated to but before the loaded event is raised. It’s there so that you can process the fragment that has been sent through to your page. Of course, it’s suited to cases where you only want to pass through a single value.

Leave a comment