Using the Navigation Framework in Silverlight 3

Posted by: Harsh Bardhan , on 3/30/2009, in Category Silverlight 2, 3, 4 and 5
Views: 52893
Abstract: In Silverlight 2, one of the challenges faced by developers was navigation between pages. It was not easy to navigate from one Xaml page to the other. In Silverlight 3, Microsoft has introduced the Navigation Framework. In this article, we will explore the Navigation Framework in Silverlight 3 and see a demo of it.
Using the Navigation Framework in Silverlight 3
 
In Silverlight 2, one of the challenges faced by developers was navigation between pages. It was not easy to navigate from one Xaml page to the other. In Silverlight 3, Microsoft has introduced the Navigation Framework. In this article, we will explore the Navigation Framework in Silverlight 3 and see a demo of it. I assume you have upgraded your development environment from Silverlight 2 to Silverlight 3.
To use the Navigation framework, we have a separate template in Silverlight 3 for creating a navigation project called ‘Silverlight Navigation Application’ (check screenshot below). Now we can navigate between different Xaml pages by clicking even the browser’s Next and Previous button, if there is browser history associated with that. We can work with Navigation Framework in a normal Silverlight Project too without using this template. All you have to do is add a reference to the System.Windows.Controls.Navigation dll but I will pick the Navigation project template for our sample as using it makes it easy to create many pages and the template also creates all the bindings by default. Let us get started:
Step 1: At first, we will create a new Silverlight Application. Open Visual Studio 2008 > File > New Project > Select the language (C# or VB.NET) > Select ‘Silverlight’ in the Project Types > from the templates, select ‘Silverlight Navigation Application’ Template (this template is new in Silverlight 3)
Step 2: Type a name (“Navigation Application”), location for the project> and click OK (see Figure below).
Navigation Template
On clicking OK, now choose the first option ‘Add a new ASP.NET Web project to the solution to host Silverlight’ and the project type as ‘ASP.NET Web Site’ and click OK as shown in the figure below
New App
You will see that two projects are created: NavigationApplication.Web and NavigationApplication.
Step 3: You will observe that a couple of new files have already been added in your Silverlight Project. If you go through the ‘MainPage.xaml’, you will find there are a couple of buttons already added and there is reference to the System.Windows.Controls.Navigation dll. At the end of the page, you will also find a Frame tag similar to the following:
 
<navigation:Frame x:Name="Frame" Source="/Views/HomePage.xaml"
  HorizontalContentAlignment="Stretch"
    VerticalContentAlignment="Stretch"
         Padding="15,10,15,10"
      Background="White"/>
‘Frame’ is the core of the navigation framework. When your application will load, the ‘Source’ attribute in the Frame will identify which page will be loaded at start.
Step 4: If you observe, there are couple of buttons on our page and every button click event has the same handler (NavButton_Click). On checking the code of the handler, we find that the code is redirecting to different Pages based on tag’s of different buttons, as shown below:
C#
private void NavButton_Click(object sender, RoutedEventArgs e)
{
    Button navigationButton = sender as Button;
    String goToPage = navigationButton.Tag.ToString();
    this.Frame.Navigate(new Uri(goToPage, UriKind.Relative));
}
 
VB.NET
Private Sub NavButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Dim navigationButton As Button = TryCast(sender, Button)
      Dim goToPage As String = navigationButton.Tag.ToString()
      Me.Frame.Navigate(New Uri(goToPage, UriKind.Relative))
End Sub
Step 5: Let’s run the application and click on the different buttons ‘Home’, ‘About’ etc. We  find that after the first click, the browser Back button gets enabled. Also observe that the Browser’s title changes on every click and navigation. Now click the back button and you will observe that now the Browser’s forward button gets enabled. You will also notice that the corresponding xaml file name is appended at the end of that. If you want to avoid this, check a cool video by Tim http://silverlight.net/learn/learnvideo.aspx?video=187319
Step 6: We will modify a few things in this application.
First, add a new ‘Silverlight page’ as shown below. Silverlight Page is a new template provided with Silverlight 3. Name it as ContactUs.Xaml .You can add a ‘Silverlight User Control’ also
New Item
Step 7: Now add a TextBlock to your ContactUs.xaml file.
Your xaml will look similar to the following:
<UserControl x:Class="NavigationApplication.ContactUs"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock Text="This is Contact Us Page"></TextBlock>
    </Grid>
</UserControl>
 
Step 8: Open your MainPage.xaml and add couple of more buttons. Your markup should look similar to the one shown here. All we have done is added two more buttons for navigating to the Next and Previous pages.
 
<UserControl x:Class=" NavigationApplication.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation">
<Grid x:Name="LayoutRoot" Background="{StaticResource ApplicationBackgroundColorBrush}">
    <Grid Style="{StaticResource NavigationContainerStyle}">
        <Border Style="{StaticResource NavigationBorderStyle}">
            <StackPanel Style="{StaticResource NavigationPanelStyle}">
                <Button Click="NavButton_Click" Tag="/Views/HomePage.xaml" Content="Home"
                        Style="{StaticResource PageLinkStyle}"/>
                <Button Click="NavButton_Click" Tag="/Views/AboutPage.xaml" Content="About"
                        Style="{StaticResource PageLinkStyle}"/>
                <Button Click="NavButton_Click" Tag="/ContactUs.xaml" Content="Contact Us"
                        Style="{StaticResource PageLinkStyle}"/>
                <Button Click="btnPrevious_Click" x:Name="btnPrevious" Content="PreviousPage"
                        Style="{StaticResource PageLinkStyle}"/>
                <Button x:Name="btnNext"  Click="btnNext_Click"  Content="NextPage"
                        Style="{StaticResource PageLinkStyle}"/>
            </StackPanel>
        </Border>
    </Grid>
    <Border Style="{StaticResource FrameContainerStyle}">
        <Border Style="{StaticResource FrameInnerBorderStyle}">
            <navigation:Frame x:Name="Frame" Source="/Views/HomePage.xaml"
                              HorizontalContentAlignment="Stretch"
                              VerticalContentAlignment="Stretch"
                              Padding="15,10,15,10"
                              Background="White"/>
        </Border>
    </Border>
</Grid>
</UserControl>
 
Step 9: Having added our buttons, some things to keep in mind and what I would particularly like to demonstrate, are the Properties like CanGoForward, CanGoBack - Methods like GoBack(),GoForward() and a couple of events.
We will use a MessageBox in this sample to show their order of occurance. Our code behind will look like this.
C#
 
public partial class MainPage : UserControl
{
public MainPage()
{
    InitializeComponent();
 
    //This will be called when frame is already navigated
    this.Frame.Navigated += new NavigatedEventHandler(Frame_Navigated);
    //This will be called When frame is navigating
    this.Frame.Navigating += new NavigatingCancelEventHandler(Frame_Navigating);
    //For handling any error while navigation
    this.Frame.NavigationFailed += new NavigationFailedEventHandler(Frame_NavigationFailed);
}
 
void Frame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
    MessageBox.Show("Navigation Failed Due to " + e.Exception.ToString());
}
 
void Frame_Navigating(object sender, NavigatingCancelEventArgs e)
{
    MessageBox.Show("Frame is navigating");
}
 
void Frame_Navigated(object sender, NavigationEventArgs e)
{
    MessageBox.Show("Frame is navigated");
}
 
private void NavButton_Click(object sender, RoutedEventArgs e)
{
    Button navigationButton = sender as Button;
    String goToPage = navigationButton.Tag.ToString();
    this.Frame.Navigate(new Uri(goToPage, UriKind.Relative));
}
 
private void btnNext_Click(object sender, RoutedEventArgs e)
{
    //For Handling NextButton Click on Top
    if (this.Frame.CanGoForward)
    {
        this.Frame.GoForward();
    }
    else
    {
        MessageBox.Show("You can not go Forward");
    }
}
 
private void btnPrevious_Click(object sender, RoutedEventArgs e)
{
    //For Handling our Previos button click
    if (this.Frame.CanGoBack)
    {
        this.Frame.GoBack();
    }
    else
    {
        MessageBox.Show("You can not go back");
    }
}
 
}
 
 
VB.NET
Partial Public Class MainPage
      Inherits UserControl
Public Sub New()
      InitializeComponent()
 
      'This will be called when frame is already navigated
      AddHandler Frame.Navigated, AddressOf Frame_Navigated
      'This will be called When frame is navigating
      AddHandler Frame.Navigating, AddressOf Frame_Navigating
      'For handling any error while navigation
      AddHandler Frame.NavigationFailed, AddressOf Frame_NavigationFailed
End Sub
 
Private Sub Frame_NavigationFailed(ByVal sender As Object, ByVal e As NavigationFailedEventArgs)
      MessageBox.Show("Navigation Failed Due to " & e.Exception.ToString())
End Sub
 
Private Sub Frame_Navigating(ByVal sender As Object, ByVal e As NavigatingCancelEventArgs)
      MessageBox.Show("Frame is navigating")
End Sub
 
Private Sub Frame_Navigated(ByVal sender As Object, ByVal e As NavigationEventArgs)
      MessageBox.Show("Frame is navigated")
End Sub
 
Private Sub NavButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Dim navigationButton As Button = TryCast(sender, Button)
      Dim goToPage As String = navigationButton.Tag.ToString()
      Me.Frame.Navigate(New Uri(goToPage, UriKind.Relative))
End Sub
 
Private Sub btnNext_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      'For Handling NextButton Click on Top
      If Me.Frame.CanGoForward Then
            Me.Frame.GoForward()
      Else
            MessageBox.Show("You can not go Forward")
      End If
End Sub
 
Private Sub btnPrevious_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      'For Handling our Previos button click
      If Me.Frame.CanGoBack Then
            Me.Frame.GoBack()
      Else
            MessageBox.Show("You can not go back")
      End If
End Sub
 
End Class
 
Now run your application.
 
Run App
 
You will find how easy it is to move from one page to other page using Silverlight Navigation framework. You will also be able to catch different events, while navigating from one xaml page to other page. These events (and their order of execution) are of immense importance and I am sure you will realise that once you start working with them. I hope you enjoyed this new feature in Silverlight 3.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Author bio not available


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Alex on Sunday, April 12, 2009 3:30 AM
You could use the Navigaton Framework even without creating the "Navigation Application" - see here: http://blogs.microsoft.co.il/blogs/alex_golesh/archive/2009/04/02/silverlight-3-quick-tip-6-navigation-framework-and-uri-routing.aspx

Regards,
Alex
Comment posted by Harsh Bardhan on Wednesday, April 15, 2009 4:25 AM
You are correct in telling that.But if you will go through this article you will find that i have mentioned initailly this point that by using  System.Windows.Controls.Navigation dll we can use navigation features.
Comment posted by Comment posted by Alex on Sunday, April 12, 2009 3:30 AM on Friday, September 11, 2009 5:42 PM
Comment posted by Alex  on Sunday, April 12, 2009 3:30 AM      
You could use the Navigaton Framework even without creating the "Navigation Application" - see here: http://blogs.microsoft.co.il/blogs/alex_golesh/archive/2009/04/02/silverlight-3-quick-tip-6-navigation-framework-and-uri-routing.aspx
Comment posted by bpS Rajput on Monday, December 27, 2010 4:16 AM
Thanks a lot. This post is very help full to me.
Comment posted by Umut on Wednesday, September 14, 2011 9:12 AM
This is a great article thanks for your work !..
Comment posted by deepak0707 on Friday, January 20, 2012 11:31 AM
http://interview-development.blogspot.com/2012/01/navigation-in-silverlight.html is good for understanding navigation in silverlight :)

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook