/Expression/ Silverlight Tutorial: Deep Links into Rich Silverlight Content

15/10/2009 | Filed under Discover > Expression

Microsoft’s Mike Taulty creates a rich application that surfaces URLs to its content

What You’ll Need
In order to work through these tutorials you will need to have installed the Silverlight Version 3 SDK (download here) and either a full version or the trial version of Expression Blend 3 (download here).


Tutorial

One of the great features of Silverlight 3 is the ability to provide hyperlinks that jump into content that is being displayed by Silverlight. Often, Rich Internet Applications do not work like the rest of the web in that there is a hyperlink to the application itself but the rest of its content is treated like a ‘black box’. In this tutorial you will create a simple master/detail application that surfaces URLs to its content even though that content is all inside of a single Silverlight application.

Note – wherever this tutorial makes use of a particular panel (e.g. “the Data Panel”) inside of Expression Blend that panel can be displayed/hidden by using the Window menu and then moved in the environment to suit your needs so your environment may not look exactly as the pictures embedded here.

1 – Create the Silverlight Project

Use the File|New Project... menu in Expression Blend to raise the “New Project” dialog and choose a “Silverlight 3 Application + Website” project and provide a suitable name for your project as below;



2 – Add a Reference to Expression Blend Interactivity Libraries

You are going to make use of some additional Expression Blend libraries so use the Projects Panel and the right-mouse-menu on the project folder itself;


In order to add references to two additional .NET assemblies containing navigation framework code. These assemblies reside in your equivalent of [C:\Program Files\Microsoft SDKs\Expression\Blend 3\Interactivity\Libraries\Silverlight] and are highlighted below;


The project structure will update to reflect that you have added these additional references;


3 – Adding Sample Data

To make building the project easier you will make use of sample data consisting of a set of images and some identifiers associated with them. Use the Data Panel to add a new sample data source;


and choose the “Define New Sample Data” option;


in order to raise the “Define New Sample Data” dialog. Leave all options on the dialog as they are to ensure that you create a data source called SampleDataSource at the Project level and that it is enabled when the application is running;


Within the updated Data Panel, alter the two automatically created properties in order that they are named Id and Image and are of type Number ( length 1 ) and Image as below. Note that properties are renamed by simply clicking on the existing name;





For the Image, use the Location setting to browse to a location that contains images such as c:\windows\web\wallpaper (on Windows 7, choose a sub-folder such as Architecture).

4 – Adding Frames and Pages

The navigation framework in Silverlight 3 largely relies on two concepts – Frames and Pages. The Frame provides the container and controls navigation to content displayed on Pages. Use the Projects Panel to open your MainPage.xaml file;


And then find a Frame on the Assets Panel and draw a Frame onto the design surface;



Ideally, set your Frame to fill the entire area of its parent by using the Properties Panel to zero any Margin and to set HorizontalAlignment and VerticalAlignment to Stretch and the Width and Height to Auto if they are not already;


5 – Adding Master and Detail Pages

You will now add two new pages to the product to display a master/detail style view of the images that you have made available as sample data.

Use the Projects Panel to add a new folder to the project called Pages;



Now use the right mouse menu on the new Pages folder to Add New Item... and raise the “New Item” dialog and add a new Page named as below;


Repeat the procedure and add a second page named ImageDetail.xaml as below;


Leaving your project structure something like;


6 – The MasterList Page

First, you will create a simple list to display your data. Open the MasterList.xaml page by double-clicking on it in the Projects Panel;


Now use the Assets Panel to select a ListBox;


And draw a ListBox out onto the design surface for MasterList.xaml;


Note that the size and shape of the ListBox do not matter too much here but you might like to set the ListBox margins to 0, HorizontalAlignment and VerticalAlignment to Stretch and Width and Height to Auto in order to make the ListBox fill the available space.

Now, use the DataPanel to drag and drop the Collection of the SampleDataSource you created previously onto the new ListBox;


the ListBox should now display a simple view of the sample data;


The natural next step would be to style the template that the ListBox is using for display but, for this tutorial, you will leave the default template.

6 – The ImageDetail Page

Use the Projects Panel to open the ImageDetail.xaml page. From the Assets Panel, select an Image and draw it out onto the design surface;


Again, ideally set the Margins for the Image to be zero and ensure that both HorizontalAlignment and VerticalAlignment are set to Stretch and the Width and Height set to Auto.

The idea of this ImageDetail.xaml page is to simply display a selected image at a larger size than in the ListBox on the MasterList.xaml page. The page needs to know which image to display and so here you will write a little code to pick that up from the query string and then data bind it to the Image on screen.

Firstly, use the Properties panel to set the Source of the Image to be “{Binding Image}” as below (ensure that you have the Image selected, using the “Objects and Timeline” Panel if necessary to check the selection). Find the Source property and use the button to the right of it to enter a Custom Expression;




With that in place you can use a query string parameter to select which image is to be displayed. Here you will use a very simple mechanism. Use the Projects panel to open the C# code file ImageDetail.xaml.cs behind this page;


Here you’ll find  code inside the class ImageDetail which runs when the page is navigated to;


Add a little code to interrogate the navigation framework, grab the query string parameter (called imageNumber below) and set the DataContext for data binding to the right element of sample data;

Firstly, add a Using statement to the list at the top of the file after the already existing using statements but before the class definition as below;


here is the same using statement for copy-and-paste;

using Expression.Blend.SampleData.SampleDataSource;


and then implement the OnNavigatedTo function as below;


again, here is the same code for copy-and-paste;

// Executes when the user navigates to this page.

protected override void OnNavigatedTo(NavigationEventArgs e)

{

       // Grab the query string parameter.

       int imageNumber =

                                         int.Parse(NavigationContext.QueryString["imageNumber"]);

                                 

       // Find our sample data as an application resource

       SampleDataSource sampleData =

                                         Application.Current.Resources["SampleDataSource"] as                        SampleDataSource;

                                 

       // Set this as our context for data binding

       this.DataContext = sampleData.Collection[imageNumber];

At this point, you should be able to test this page. Run the project with F5 in Expression Blend – it will be blank. Within the browser window, use a URL following the form below;


Note that the port number is dynamically generated and so may differ on your system but the important part of which is the portion after the Default.html as in;

    #/Pages/ImageDetail.xaml?imageNumber=4

Hopefully you can see how your query string parameter is being passed into your ImageDetail.xaml page by the framework.

7 – Displaying the MasterList Page at Startup

At the moment, the application is starting with a blank Frame whereas it would ideally start by displaying the MasterList page. Fix this by using the Projects Panel to open the MainPage.xaml;


And select the Frame on the design surface (or using the “Objects and Timeline” panel). Then use the Properties panel to set the Frame’s property called Source to be the MasterList.xaml page as below;


Re-run your project to ensure that at startup it does now navigate to the #/Pages/MasterList.xaml page as shown below;


8 – Navigating on Selection

At the moment, changing the selected item in the ListBox does not cause a navigation event. You could easily add a button to the ListBox item in order to facilitate this but to keep the tutorial short we will use the change of selection on the ListBox to drive the navigation.

Switch back to the MasterList.xaml file in the editor and select the ListBox on the design surface;


And in the Properties Panel select the events view in the top right;


Double click on the area to the right of the SelectionChanged event to create an event handler for this event, Expression Blend will jump to the code for that event in the code editor;


Now replace the empty implementation of ListBox_SelectionChanged with the code below to cause the Frame to navigate to the details page when the selection is changed;     


here is the same code for copy-and-paste;

private void ListBox_SelectionChanged(object sender,   System.Windows.Controls.SelectionChangedEventArgs e)

{

       // which item is selected?

       ListBox listBox = (ListBox)sender;

       int imageNumber = listBox.SelectedIndex;

                    

       // build the Uri

       Uri navigateUri = new Uri(                                                   string.Format("/Pages/ImageDetail.xaml?imageNumber={0}",

              imageNumber), UriKind.Relative);

The code finds the selected index from the ListBox and then dynamically builds a URI to navigate to.

Test your code by running the application (F5) – you should find that changing the selection in the ListBox now navigates into the details page (where each image has its own full URL) and that using the Back/Forward buttons works as expected.

9 – Tidying up the URIs

Whilst the application “works”, the URIs that it is using are ugly and not something that would be easy for a user to remember. To help with this, the navigation framework has a concept of a UriMapper that can abstract away the details of URIs.

Use the Projects Panel to open the MainPage.xaml file;


on the design surface, select the Frame (check using the “Objects and Timeline” Panel);


Now use the Properties Panel in order to find the UriMapper property ( ensure it is switched back to displaying properties using the icon at the top right as indicated )



And use the “New” button which will allow you to then use the “...” button to edit the UriMappings collection;


In the dialog raised, use the Add Another Item button;


to add two mappings to the collection as below;


Uri

MappedUri
detail
/Pages/ImageDetail.xaml
list
/Pages/MasterList.xaml

NB: the drop-down lists help here as you can select relevant values but take care with the initial forward slash character that the drop-down omits.

Re-rest the application by pressing F5. The new mappings should allow you to use URLs such as illustrated below as alternates;



About the Author

Mike Taulty works for Microsoft’s Developer and Platform Group in the UK where he promotes and educates around the Microsoft platform and tools to the broad UK community of developers and architects. You can find Mike at http://mtaulty.com