Silverlight 3 Quick Tip #6: Navigation Framework and Uri Routing

April 2, 2009

Silverlight 3 introduced the Navigation Framework and URI Routing features. Today I’ll show how to use those features.

To use navigation features you could either create a new “Silverlight Navigation Application” or simply add relevant references to standard “Silverlight application”

image

In case of standard “Silverlight Application” you need to add reference to “System.Windows.Controls.Navigation” assembly and relevant XAML introduce namespace:

xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"

To use the navigation feature, simply add new Frame to your XAML page. Frame could have default content, specify Journal usage (own history storage or integration within browser’s history), raise navigation related events.

<navigation:Frame x:Name="frame" Source="/Pages/DefaultPage.xaml"
                      HorizontalContentAlignment="Stretch"
                      VerticalContentAlignment="Stretch"
                      Padding="15,10,15,10"
                      Margin="5,0"
                      Background="White">
  <TextBlock Text="This is default content for the navigation frame" FontFamily="Times New Roman" FontSize="25"/>
</navigation:Frame>

To navigate to new page use “Navigate” function of Frame object:

frame.Navigate(new Uri(“/Pages/Page1.xaml”, UriKind.Relative));

Navigation could be done to class instances derived from “System.Windows.Controls.Page” class. The simplest way to create such a class (and XAML) is by adding to the project new item from “Silverlight Page” type:

image

In addition to navigation, the Frame provides functionality to navigate Forward/Backward according to own/browsing history. Sample “Next”/“Previous” button handlers:

private void btnNext_Click(object sender, RoutedEventArgs e)
{
  if (frame.CanGoForward)
    frame.GoForward();
}

private void btnPrev_Click(object sender, RoutedEventArgs e)
{
  if (frame.CanGoBack)
    frame.GoBack();
}

The history definition for the frame defined by JournalOwnership dependency property:

image

Automatic [default] Whether or not this Frame will create and use its own journal depends on its parent
OwnsJournal The Frame maintains its own journal
UsesParentJournal The Frame uses the journal of the next available navigation host up the content tree, if available. Otherwise, navigation history is not maintained for the Frame

 

To raise navigation related events subscribe to themNext:

//This event will be fired when frame is already navigated
this.frame.Navigated += new NavigatedEventHandler(frame_Navigated);
//This event will be fired when frame is navigating
this.frame.Navigating += new NavigatingCancelEventHandler(frame_Navigating);
//This event will be fired when navigation error occurs
this.frame.NavigationFailed += new NavigationFailedEventHandler(frame_NavigationFailed);

By using this Navigation Framework features you could implement deep linking support by URI Routing feature. To use this feature you need to create the UriMapper in application resources. To do so first you need to introduce a namespace in your App.XAML:

xmlns:navcore="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation"

Then create the UriMapper as a part of application resources:

<Application.Resources>
  <navcore:UriMapper x:Key="uriMapper">
    <navcore:UriMapping Uri="Home" MappedUri="/Pages/DefaultPage.xaml"/>
    <navcore:UriMapping Uri="Link{number}" MappedUri="/Pages/Page{number}.xaml"/>
    <navcore:UriMapping Uri="Page/{number}" MappedUri="/Pages/Page{number}.xaml"/>
    <navcore:UriMapping Uri="Customers/{id}" MappedUri="/Pages/Page1.xaml?action=getCustomer&amp;id={id}"/>
    <navcore:UriMapping Uri="Products/{id}" MappedUri="/Pages/Page1.xaml?action=getProduct&amp;id={id}"/>
    <navcore:UriMapping Uri="Stories/{id}&amp;{number}" MappedUri="/Pages/Page1.xaml?action={id}&amp;page={number}"/>
  </navcore:UriMapper>
</Application.Resources>

In Beta 1 build the Uri Mapper must have “uriMapper” name, otherwise it will not work.

In my case the mapping is very straightforward:

Uri Target + Description
Home /Pages/DefaultPage.xaml
Link{number} /Pages/Page{number}.xaml –-> use {number} as variable received from navigation input
Page/{number} /Pages/Page{number}.xaml –-> use {number} as variable received from navigation input
Customers/{id} /Pages/Page1.xaml?action=getCustomer&amp;id={id} –-> use {id} as part of Query String
Products/{id} /Pages/Page1.xaml?action=getProduct&amp;id={id} –-> use {id} as part of Query String
Stories/{id}&amp;{number} /Pages/Page1.xaml?action={id}&amp;page={number} –> use {id} and {number} in Query String. You could introduce as many, as you need.

When navigating, the navigating URI becomes something much more readable (and SEO):

image

image

image

image

The passed query string parameters could be used on specific page from NavigationContext. While creating new “Silverlight Page” visual studio also creates override function “OnNavigatedTo” which being executed right after navigation to the page:

// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
  if (this.NavigationContext.QueryString.ContainsKey("action"))
  {

    switch (this.NavigationContext.QueryString["action"])
    {
      case "getCustomer":
        txtOutput.Text = "This is DUMMY info CustomerID = " + this.NavigationContext.QueryString["id"];
        break;
      case "getProduct":
        txtOutput.Text = "This is DUMMY info ProductID = " + this.NavigationContext.QueryString["id"];
        break;
      default:
        txtOutput.Text = "This is DUMMY story saved in my sources with ID = " 
          + this.NavigationContext.QueryString["action"] + " opened on page #" 
          + this.NavigationContext.QueryString["page"];
        break;
    }
  }
}

That’s it for today.

Sample application sources is here.

 

Enjoy,

Alex

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

35 comments

  1. phucndApril 13, 2009 ב 7:33

    thanks for this post!

    Reply
  2. MatanJune 25, 2009 ב 16:12

    Thank you so much for presenting this subject in a clear mannor, and it works!

    Reply
  3. SundeepDecember 11, 2009 ב 11:42

    Dear Alex,
    I have problem with URI mapping.Please solve this issue.I have Two main pages and one navigating iframes in each main page in my project.On Visit of First main page,I redirect the Iframe source to some page(Normal SL page) on Click of Button X.I have another Button Y which on click Switches to Another main page.the issue is,Before Clicking Button Y,If i have visited any Child page(Using Iframe) in First main page,the same page is being shown in Second page Iframe.What i mean to say is, the Urimapped source(Shown in addressbar) which i visited in First main page is still shown in second main page visit.I don’t want to see URI mapped source in address bar.
    Can You help me regarding this.

    Reply
  4. Alex GoleshDecember 11, 2009 ב 20:26

    Sundeep: I’m not sure, that I understood what you trying to do. Could you give me the complete scenario of what you trying to achive?

    Alex

    Reply
  5. AndyDecember 29, 2009 ב 3:41

    Hmmm. This Silverlight seems to be more difficult to figure out than Linux (I wonder if it’s because MS wants me to buy Blend?)

    I wonder if my question is similar to Sundeeps. What I want to do is basically this…

    I have a logon screen. I don’t want any of the hyperlinkbuttons (main page) to appear until a user has logged in. I also don’t want to use a hyperlinkbutton to logon, but a regular button.

    I’m looking at the default pageNavigation example in Visual Web Dev 2k8 Express. I’m wondering what the block of urimappers are at the top.

    I can’t for the life of me figure out how I can get a (logon) page to direct to a page (in the same project) that uses a set of hyperlink buttons to navigate within the main app.

    I can be emailed at armills {at} hotmail.com

    Thanks!

    Reply
  6. Texas Westside escort agencyJanuary 2, 2010 ב 21:31

    It was extremely interesting for me to read the blog. Thanks for it. I like such themes and everything that is connected to this matter. I would like to read more on that blog soon.

    Reply
  7. Ashok NJanuary 22, 2010 ב 11:15

    Can you please give me sample application for my following requirement -
    I want a layout with -
    1. Header.
    2. Left Navigation (Collapsible Menu)
    3. Content Page. (It should change as per the click on Collapsible Menu item).
    4. Footer (with Current Content Page Name).
    5. One Full Screen Button.
    Can you please send me the above functionality ASAP. I have an urgent requirement. All should be in Silverlight Application only. Please Please …..

    |—————————————————————|
    | Header.xaml |
    |—————————————————————|
    | | |
    |left.xaml | content.xaml |
    | | |
    |Full Screen Btn| |
    |—————————————————————|
    footer.xaml |
    |—————————————————————|

    My Mail ID: ashok.just4u@gmail.com

    Reply
  8. Alex GoleshJanuary 22, 2010 ב 11:31

    Ashok:
    I don’t have application with the spec muches you one, and will don’t have a time to make your work. If you have some specific problem creating one will be glad to ANSWER your questions.

    Regards,
    Alex

    Reply
  9. Ashok NFebruary 11, 2010 ב 12:44

    Hi,
    Thanks for your reply. I got below problems after creating above mentioned layout -
    1. Before and after click on “Full Screen Button” the size of text was changing.
    2. For example first my system resolution is in 1024 X 768. If I re-size my silver light IE window I want scrolling. If I change my system resolution grater than above resolution the I don’t want scrolling. at that time also if I re-size my IE window i just want scrolling. (In both cases if I maximize my page the silver light page should view complete).
    Finally To implement scroll ability when the window size is altered
    3.My applications should support with all resolutions.

    Reply
  10. pualAugust 25, 2010 ב 8:19

    after running the sample what i found that url is not mapped..its shows as file:///C:/Project/NavigationDemo_1/NavigationDemo/Bin/Debug/TestPage.html#/Pages/Page1.xaml. Again you have declared the mapping code in app.xmal and when we run the application how navigation frame define in main page gets link with the url mapping defined in app.xmal. Plese guide me

    Reply
  11. MAHESH BABU UMMANENIDecember 6, 2011 ב 15:41

    I AM NEW TO SILVER LIGHT,I TOOK ONE PAGE(PAGE1.XAML) AND I TOOK ONE MORE PAGE(PAGE2.XAML), IN PAGE1.XAML I HAD ONE BUTTON WHEN I CLICK I WANT SHOW PAGE2.XAML USING CLICK EVENT.I THINK ITS VERY SILLY QUESTION

    Reply
  12. SamyMay 15, 2012 ב 16:37

    Hi Alex , I have a problem , I have 2 differents pages and want to navigate between them without losing the information I already binded in one of the pages…

    I really don’t understand how I should do that

    can you help ?

    Reply
  13. FiteAugust 6, 2012 ב 12:51

    There is certainly a lot to find out about this topic.
    I like all the points you’ve made.

    Reply
  14. CornettNovember 13, 2012 ב 1:01

    I was able to find good advice from your articles.

    Reply
  15. CazaresNovember 13, 2012 ב 9:10

    Informative article, totally what I needed.

    Reply
  16. SeymourDecember 15, 2012 ב 11:13

    Why users still make use of to read news papers when in this technological world the whole thing is presented on net?

    Reply
  17. CoppolaDecember 15, 2012 ב 22:25

    This site certainly has all of the info I wanted about this subject and
    didn’t know who to ask.

    Reply
  18. MacklinDecember 18, 2012 ב 0:19

    I really like it whenever people get together and share thoughts.
    Great site, stick with it!

    Reply
  19. GilmerDecember 19, 2012 ב 9:08

    Hi everyone, it’s my first pay a quick visit at this web page, and piece of writing is really fruitful designed for me, keep up posting such posts.

    Reply
  20. SilverDecember 19, 2012 ב 22:52

    This is a topic which is close to my heart… Best wishes!
    Exactly where are your contact details though?

    Reply
  21. BufordDecember 26, 2012 ב 15:29

    I was able to find good advice from your blog posts.

    Reply
  22. CavazosDecember 31, 2012 ב 10:23

    Actually when someone doesn’t understand after that its up to other viewers that they will assist, so here it takes place.

    Reply
  23. PriceJanuary 6, 2013 ב 22:59

    Appreciate the recommendation. Will try it out.

    Reply
  24. LillyJanuary 12, 2013 ב 7:39

    Hi, after reading this amazing piece of writing i am also cheerful to share my
    experience here with colleagues.

    Reply
  25. PackardJanuary 17, 2013 ב 11:06

    My family all the time say that I am wasting my time here at net,
    except I know I am getting know-how daily by reading thes good posts.

    Reply
  26. MaesJanuary 18, 2013 ב 3:06

    I got this site from my buddy who shared with me concerning this web
    page and now this time I am browsing this site and reading very informative articles or reviews at this time.

    Reply
  27. GardnerJanuary 21, 2013 ב 20:51

    I’ve recently started a website, the info you provide on this web site has helped me greatly.
    Thanks for all of your time & work.

    Reply
  28. OneillJanuary 23, 2013 ב 19:12

    If you desire to improve your experience just keep visiting this web page
    and be updated with the hottest gossip posted here.

    Reply
  29. HamiltonJanuary 24, 2013 ב 4:00

    It’s very effortless to find out any topic on web as compared to books, as I found this piece of writing at this web site.

    Reply
  30. AlbertsonJanuary 26, 2013 ב 12:21

    I like reading an article that can make men and women think.

    Also, thank you for allowing for me to comment!

    Reply
  31. ValentineJanuary 30, 2013 ב 0:27

    Hi there mates, how is everything, and what you
    wish for to say concerning this article, in my
    view its truly awesome in support of me.

    Reply