Loading Query Strings with Silverlight Navigation Applications

Scenario

Your Silverlight application has navigation URLs which contain a lot of optional parameters. e.g.

http://yourhost/sl.htm#/Home?filterUser=1&filterCategory=2&filterStartDate=2010-10-25

Each of these have to be checked whether they are present or not.

Solution

Using the NavigationContextExtensions, you can do the following

  /* Note
     string    CompanyFilter {get; set; }
     int?      SiteFilter {get; set; }
     DateTime? StartDate {get; set; }
  */

  this.vm.CompanyFilter = NavigationContext.QueryStringOrNull("company");
  this.vm.SiteFilter = NavigationContext.QueryStringOrNull<int>"siteid", Convert.ToInt32);
  this.vm.StartDateFilter = NavigationContext.QueryStringOrNull<DateTime>("stardate", Convert.ToDateTime);

Here’s the supporting class:

namespace ProjectNavigation.Helpers
{
    public static class NavigationContextExtensions
    {
        public static string QueryStringOrNull(this NavigationContext NavigationContext, string key)
        {
            if (NavigationContext.QueryString.ContainsKey(key))
            {
                return NavigationContext.QueryString[key];
            }
            else
            {
                return null;
            }
        }
        public static T? QueryStringOrNull<T>(this NavigationContext NavigationContext, string key, Func<string, T> converter) where T:struct
        {
            if (NavigationContext.QueryString.ContainsKey(key))
            {
                return converter(NavigationContext.QueryString[key]);
            }
            else
            {
                return null;
            }
        }
    }
}