May 6, 2009

Navigation in Silverlight 3 - enhanced a lot from 2!

Silverlight 3 is going to bring a whole lot of new stuff to the Silverlight consept. It will contain at least approximately 90% of WPF features, and a lot of web-related features in addition. One of the coolest things it brings, from my point of view at least, is the navigation framework. Creating navigation in Silverlight 2 was elaborate, if nothing else. Now, in Silverlight 3, we've got a ready framework for it!

The easiest way to get started with a navigational Silverlight site, is to create the project in VisualStudio and choose the Silverlight Navigation Application -project. Not necessary, but makes getting started a whole lot easier, for it contains the necesary references and namespaces from the beginning. It also contains a lot of example code, from which to extend your own application. The downside is that of course, the UI is fully prepared to, so you actually will need to tear it down and rebuild it anyway. But, for exploring the navigation functionality, the example code serves well.

This navigation  framework relies on a navigational frame to which Silverlight Pages are referred. The simple scenario is, that in the main frame (working sort of like a master page) you have link buttons and the frame in which the pages are shown. The xaml (of the example) is for the buttons (inside a stack panel):



and for the navigational frame:



Notice that there are also some static resourses applied here - you can either modify them or make your own ones. 

To extend this Silverlight application, that is, to add pages to it, all you really need to do (well, skipping all the design stuff here), is create new Silverlight Pages to the Views folder and then add the link buttons to the stack panel acoordingly. 

You can also go a step further if you wish. You can create an xml file to contain all information of your site navigation and then populate the link bar by binding the data from the xml file to the link buttons, via a class. This requires of course a few more steps than the simple scenario, but might prove worth its while. I stumbled accross this in the Silverlight Toys -blog, so instead of creating my own tutorial here, I refer to the original, as it is a rather good one: http://www.silverlighttoys.com/tutorials.php?tutorial=1

With only one addition, regarding the loading and binding: it is not actually enough to simply write the MainPage_Loaded -method, for even though it does go through the build ok, the application doesn't actually run the method at all since it's not intantiated anywhere. So, in order to make the thing work, add the phrase
this.Loaded += MainPge_Loaded;
to the public MainPage -code section (under InitializeComponent(); ).  Also, the SetPage method does not exist and is also unnecessary when the start page is set in the navigation frame.

No comments: