Silverlight Navigation Framework

,Navigation Application Template


Silverlight Navigation Application Template

.Navigation Framework

"Silverlight's built-in navigation is browser-oriented and consists of a single Frame control containing one or more Page controls. The built-in navigation is integrated with the browser so that the browser's back and forward buttons control the application paging."

Developers can create their own navigation in Silverlight applications or they can use the built-in navigation system. Implementing a custom navigation system can add the benefits of authentication redirects and other specialized navigation behaviors. However a custom navigation system will require the developer to add controls and logic for moving from one page to another. The built-in navigation system simplifies the development of page navigation within an application. The built-in navigation is integrated with the browser's back and forward buttons so that the browser's back/forward buttons are used to move between the application's pages. Custom navigation will not automatically contain the browser integration, in which case using the browser's back button will exit the application instead of moving to a previous page in the application.

Note: Silverlight for Windows Phone provides a modified version of the navigation system which uses the PhoneApplicationFrame and PhoneApplicationPage classes. See articles on sister site: Windows Phone Navigation and Page Layout and Lab3: Windows Phone Navigation and Controls for navigation information specific to Windows Phone.



Silverlight Navigation Framework

The navigation framework handles the process of page navigation within an application. The framework supports:

  1. Back and Forward Navigation - integrated with browser to allow browser's back/forward buttons to move between the application's pages.
  2. Journal Histories - stores the browsing page history so users can navigate back and forth on the pages visited in the current session.
  3. Deep Linking - allows navigation directly to any page inside the application. The pages are considered fragments of the application and the # symbol is used in the URI to encode the page address.
  • Silverlight's navigation framework uses the Frame and Page classes to provide navigation controls:
    • Frame:
      • is a top-level ContentControl (only one child) which integrates with the browser journal (by default) and facilitates navigation to Silverlight pages.
      • is typically only declared and assigned once per application. If the application uses multiple frames, one frame must be designated as the main frame and the other frames must turn off the journal history (Frame.JournalOwnership = OwnsJournal) and track their own navigation.
      • The frame (or mainframe) needs to be associated with the Application.RootVisual property when the application starts. Inside App.xaml.cs, in the Startup event, the RootVisual property of the application class is set to the class which contains the frame:

                private void Application_Startup(object sender, StartupEventArgs e)
                {
                    this.RootVisual = new MainPage();
                }

      • The Frame control is defined inside the main page (as specified by Application.RootVisual) :

                    <Border x:Name="ContentBorder" Style="{StaticResource ContentBorderStyle}">

                    <navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}"
                                      Source="/Home" Navigated="ContentFrame_Navigated" NavigationFailed="ContentFrame_NavigationFailed">
                        <navigation:Frame.UriMapper>
                          <uriMapper:UriMapper>
                            <uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
                            <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
                          </uriMapper:UriMapper>
                        </navigation:Frame.UriMapper>
                    </navigation:Frame>
                </Border>

      • The Frame class contains the following properties:
        1. CacheMode - when enabled causes previously visited pages (with page state) to be loaded from memory instead of being recreated (default is disabled).
        2. CacheSize - specifies the number of pages to keep in cache memory (defaults to 10).
        3. CanGoBack - indicates if there is at least one entry in the back navigation history.
        4. CanGoForward - indicates if there is at least one entry in the forward navigation history.
        5. ContentLoader- allows specification of a Custom Content Loader. A Customer Content Loader is a class which implements (NavigationContentLoader to contain the logic for accepting the URI and displaying the contents.
        6. JournalOwnership - indicates if the frame is responsible for maintaining its own navigation history, or instead integrates with the Web browser history journal. Default is Automatic (integrates with browser journal). To maintain your own navigation history set to OwnsJournal.(
        7. Source indicates the URI for navigation.
        8. *UriMapper - converts a URI during the navigation process.
        9. *Style - set the display styling for the frame.
      • The Frame class contains the following methods:
        1. GoBack - navigates to the most recent entry in the back history.
        2. GoForward - navigates to the most recent entry in the back history.
        3. Navigate - navigates to the content specified by the URI
      • The Frame class contains the following events:
        1. FragmentNavigation - triggered when navigated to a specified page (fragment).
        2. *Navigated - trigged when page is no longer the active page in the frame
        3. Navigating - trigged just before a page is swapped with another page
        4. *NavigationFailed - trigged when page fails to load.
        5. onNavigatedTo - trigged when page becomes the active page in the frame (most commonly used Frame event).
    • Page:
      • The Page class provides a navigation-aware user control.
      • A page can be defined by using xaml, a combination of xaml and code, or just code.
      • A page is a direct child of a Window, NavigationWindow, or Frame element in XAML.
      • The Page class contains the following properties:
        1. NavigationCacheMode - Determines page caching (Disabled=No Caching; Required=Always Cache; Enabled=Cache with Limit).
        2. NavigationContext - Gets an object that contains information about the navigation request.
        3. NavigationService - Gets the service that the host used to navigate to this page..
        4. Title - Gets or sets the name for the page..
      • The Page class contains the following methods:
        1. OnFragmentNavigation - Called when navigating to a fragment on a page.
        2. OnNavigatedFrom - Called when a page is no longer the active page in a frame.
        3. OnNavigatedTo - Called when a page becomes the active page in a frame..
        4. OnNavigatingFrom - Called just before a page is no longer the active page in a frame.
      • includes three methods which are called during page transitions:
        • OnNavigatedTo - called when a page becomes the active page in a frame:
          • retrieve the page state data during or after the method has been called.
        • OnNavigatedFrom - called when a page is no longer the active page in a frame.:
          • store the page state data during or before the method is called
        • OnNavigatingFrom - called just before a page is no longer the active page in a frame:
          • allows the navigation to be redirected or canceled.

    Navigation Application Template

    Silverlight contains a Silverlight Navigation Application template which can be used as a starting point for creating applications containing page navigation. The navigation template application contains a Views folder which contains the .xaml files for the pages. New pages are added to the application by:

    1. Add a new page to the Views folder - right-click on View folder, Add, New Item, Silverlight Page template.

    2. Add a link to the new page in the navigation menu - Add a new HyperlinkButton for the page in NewPage.xaml:

      <HyperlinkButton x:Name="Page1"
        Style="{StaticResource LinkStyle}"
        NavigateUri="/Page1"
        TargetName="ContentFrame"
        Content="Page 1" />

      <Rectangle x:Name="Divider2"
        Style="{StaticResource DividerStyle}" />

.Solution Explorer for Navigation Template


Navigation Application Template - Solution Explorer

Navigation Events

  • onFragmentNavigation - triggered when navigated to a fragment (equivalent to HTML's hashtag navigation.
  • onNavigatedFrom - trigged when page is no longer the active page in the frame.
  • onNavigatedFrom - trigged just before a page is swapped with another page.
  • onNavigatedTo - (most commonly used) trigged when page becomes the active page in the frame.


NavigationService Class

  • In the code behind file the NavigationService class is used to control navigation. The class contains five methods:
    • GoBack - navigates to previus entry in active history journal.If no entry is available, then an exception occurs.
    • GoForward - navigates to next entry in active history journal.If no entry is available, then an exception occurs.
    • Navigate - navigate to specifed URI.
    • Refresh - reload the current page.
    • StopLoading - cancel an asynchronous navigation action that hasn't been processed yet.
  • Use properties to test if an entry exists in the journal before navigating forward or back to avoid the expection that will occur if no entry exists. (eg. NavigationService.CanGoBack).


      if (this.NavigationService.CanGoBack)
      {
       this.NavigationService.GoBack();
      }

UriMapper Class

  • The UriMapper class maps a uniform resource identifier (URI) into a new URI based on specified rules.
  • The UriMapper class is used to:
    • Hide the real physical navigation structure (or display a more user friendly URI in the browser).
    • Provide suitable query strings parameters to pages.
  • The Uri property specifies the url that is displayed in the browser address window and the MappedUri property specifies the url that is mapped when the Frame navigates to the specific page
  • Below is an example of mapping a blank URI to a homepage URI:

    <sdk:Frame.UriMapper>
     <sdk:UriMapper>
      <uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
     <sdk:Frame.UriMapper>
    <sdk:UriMapper>

  • Below is an example of several URI mappings :

    <sdk:Frame.UriMapper>
     <sdk:UriMapper>
      <sdk:UriMapping
       Uri="/ProductDetail/{productid}"
       MappedUri="/Views/ProductDetail.xaml?ProductId={productid}"/>
      <sdk:UriMapping
       Uri="/Reports/{type}/{selection}"
       MappedUri="/Views/ReportsPage.xaml?type={type}&amp;selection={selection}"/>
      <sdk:UriMapping
       Uri="/{pageName}"
       MappedUri="/Views/{pageName}.xaml"/>
     <sdk:Frame.UriMapper>
    <sdk:UriMapper>

  • Mappings are read starting from the top and stop once the first match is found.


Implementing Caching

  • By default, the navigation framework creates a new instance of each navigated page (even for the back button).
  • Page caching is enabled with the NavigationCacheMode property on the Page element, which can have the values:
    • Disabled - (default) no caching.
    • Required - always use the cached version of the page
    • Enabled - cache the page, but discard the cached pages once the cache limit has been reached.
  • The default size of the cache limit is set to 10 pages. Use the CacheSize property to change the cache limit value.
  • The OnNavigatedTo method is called for each request, even when the page is retrieved from the cache. You should include in this method code that must be executed for each request rather than placing that code in the Page constructor.
  • Example of enabling a page to be cached:

    <sdk:Page
      x:Class="NavExample.Views.PerformanceSchedule"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
      Title="Current Month's Performance Schedule"
      NavigationCacheMode="Enabled">

      <Grid x:Name="LayoutRoot">

      </Grid>
    </sdk:Page>



Reference Articles


Top