Navigation Widgets and Styles in Microsoft Silverlight 4

Exclusive offer: get 50% off this eBook here
Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide — Save 50%

Build enterprise-ready business applications with Microsoft Silverlight 4 with this book and eBook

$32.99    $16.50
by Frank LaVigne | April 2010 | Beginner's Guides Microsoft Web Development Web Graphics & Video

In this article by Frank LaVigne, author of Microsoft Silverlight 4 Business Application Development, we shall create a navigation widget in Silverlight to add to the current website.

Retrofitting a website

The first thing the client would like to do to their website is spice it up with a new navigation control and a playful, interactive logo for the top of the page. First, we'll work on a navigation control to replace the text links on the left hand side of the page of the current website. As you will notice in the following image, the current website navigation mechanism isn't fancy, but it's simple. However, the client would like the website to be more modern, while preserving ease of use.

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

Adding pizzazz with Silverlight

Cake-O-Rama would like to add a fancy navigation widget to their site. They've commissioned a graphic artist to create the following look for the widget.

 

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

A few words on search engine optimization

We could easily create a Silverlight application that would encompass all the content and functionality of a whole website. However, doing so would severely limit the website's visibility to search engines. Search engines have programs called spiders, or robots, that 'crawl' the internet scanning for content. Generally, these programs can only see text exposed in the HTML. Search results are ranked based on this text-only content. Placing all our content inside a rich internet application platform like Silverlight would effectively hide all of our content. The net result would be reduced visibility on search engines.

All Rich Internet Application (RIA) platforms have this issue with search engine visibility.

Until this problem is resolved, the best approach is to augment the page's HTML content on sites that you want to be found more easily by search engines.

Building a navigation control from the ground up

Silverlight 4 has the Grid, Canvas, StackPanel, Border, WrapPanel, ViewBox, and ScrollViewer layout panels. Why are there so many? Well, each one serves a unique purpose.

Picking the right kind of container

You wouldn't fill a cardboard box with water or drink milk out of a gasoline can, would you? The same could be said of the various layout containers in Silverlight, each one serves a unique purpose and some are better at certain tasks than others.

For instance, when you want to create a toolbar, you would probably use a StackPanel or WrapPanel , and not a Canvas. Why? While you could manually code the layout logic to place all the child controls, there's no good reason to. After all, there are already controls to do the heavy lifting for you. Below are the most common layout containers in Silverlight 4:

Container

Layout Behavior

Canvas

Manual positioning of items using X and Y coordinates

Grid

Lays out items using a defined grid of rows and columns

InkPresenter

Canvas that can handle digital ink

StackPanel

Stacks items on top of or next to one another

WrapPanel

Lines up items and wraps them around

Border

Draws a border around an item

Viewbox

Scales an item up to take up all the available space

ScrollViewer

Places a scroll bar around the control

Silverlight also provides the means to write your own layout code. While there may be situations where this is warranted, first think about how you can achieve the desired result with a combination of the existing containers.

Stack it up: Using the StackPanel

Based on the website's current navigation links, StackPanel seems like the best choice. As the name implies, it lays out child controls in a stack, which seems like a good fit for our list of links.

Time for action – building navigation buttons in Silverlight

Now, let's make a StackPanel of button controls to navigate around the site. In order to do this, we will need to do the following:

  1. Launch Visual Studio 2010 and click on File|New Project.
  2. Choose to create a new Silverlight Application as shown in the next screen:
  3. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  4. Name the project CakeNavigationButtons and click OK to accept the default settings.
  5. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  6. In the MainPage.xaml file, write the following lines of XAML inside the Grid tag:
  7. <StackPanel>
    <Button Content="Home" />
    <Button Content="Gallery"/>
    <Button Content="Order"/>
    <Button Content="Locations"/>
    <Button Content="Contact Us"/>
    <Button Content="Franchise Opportunities"/>
    </StackPanel>

  8. Return to Visual Studio 2010 and click on Debug|Start Debugging or press F5 to launch the application.
  9. On the following screen, click OK to enable debugging.
  10. Your application should look something like this:

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

We have now created a StackPanel of button controls to navigate around the website using Silverlight, but the application is not exactly visually appealing, not to mention, the buttons don't do anything. What we need them to do is reflect the design we've been provided with and navigate to a given page when the user clicks on them.

What just happened?

What we created here is the foundation for what will eventually become a dynamic navigation control. You have created a new Silverlight application, added a StackPanel, and then added button controls to it. Now, let's move on to make this little navigation bar sparkle.

Adding a little style with Styles

Many people refer to Silverlight controls as being "lookless", which may sound strange at first as they clearly have a "look." The term refers to the fact that the logic in a control defines its behavior rather than its appearance. That means that all the controls you've seen in Silverlight so far have no presentation logic in them. Their look comes from a default resource file. The good news is that we can create our own resources to customize the look of any control. You can re-style a control in Silverlight in much the same way as you can in Cascading Style Sheets (CSS).

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide Build enterprise-ready business applications with Microsoft Silverlight 4 with this book and eBook
Published: April 2010
eBook Price: $32.99
Book Price: $54.99
See more
Select your format and quantity:

Styles

For instance, what if we wanted the text in the buttons to be larger? We could add a FontSize attribute to every button control, so that our XAML code would look like this:

<StackPanel>
<Button Content="Home" FontSize="18" />
<Button Content="Gallery" FontSize="18"/>
<Button Content="Order" FontSize="18"/>
<Button Content="Locations" FontSize="18"/>
<Button Content="Contact Us" FontSize="18"/>
<Button Content="Franchise Opportunities" FontSize="18"/>
</StackPanel>

While this would give us the desired effect, it also bloats the XAML and, should we change our minds about the font size later, forces us into a situation where we'll have to do a lot of typing. A Style would provide a more elegant solution to this problem. For example, I can define a style that bumps up the FontSize to 18 as shown below:

 

<Style x:Name="biggerTextStyle" TargetType="Button">
<Setter Property="FontSize" Value="18"/>
</Style>

The above snippet of XAML actually defines a style named biggerTextStyle and declares that it is for button controls. Inside the style, there can be any number of Setter nodes. In this style, there is only one and it sets the FontSize property to 18. To use this style, we're going to need to do two things: place it into our application and tell our buttons to reference the style.

In Silverlight, styles are considered a Resource, which are any kind of data stored inside an object. Accordingly, we'll place the Style inside the Resources collection of our UserControl, which is the root element of the MainPage.XAML file. This would be analogous to the HEAD section of an HTML document, where document-wide resources reside:

<UserControl.Resources>
<Style x:Name="biggerTextStyle" TargetType="Button">
<Setter Property="FontSize" Value="18"/>
</Style>
</UserControl.Resources>

We have several options for storing resources in Silverlight. Many controls have a Resources collection and we can store resources in App.xaml, where it is accessible to the entire application. Alternatively, we can even define a Resource Dictionary, which is a separate file that contains resources. A resource dictionary is analogous to an external CSS file in HTML. Resource dictionaries can be shared across applications.

Once the style is in place, we need to tell the Button to use it by adding a reference to it in the Style attribute to the button, so the XAML for the buttons now looks like this:

<Button Content="Home" Style="{StaticResource biggerTextStyle}" />
<Button Content="Gallery" Style="{StaticResource biggerTextStyle}" />
<Button Content="Order" Style="{StaticResource biggerTextStyle}" />
<Button Content="Locations" Style="{StaticResource biggerTextStyle}"
/>
<Button Content="Contact Us" Style="{StaticResource biggerTextStyle}"
/>
<Button Content="Franchise Opportunities" Style="{StaticResource
biggerTextStyle}" />

You may be wondering what those curly braces are doing inside of an XAML document. They are a special cue for the XAML processing engine to execute certain commands, called a Markup Extension. The markup extension above tells the Silverlight runtime to set the style property to the resource named biggerTextStyle.

In each Button we reference the same biggerTextStyle Style resource for all of our buttons. This is to make sure they all use the same Style resource. This bloats our code somewhat. Wouldn't it be great if there were a way to create a default style that would apply to all the buttons in our application? Fortunately, for us this feature was added in Silverlight 4. We now have the option to define a default style for a particular type of control. Simply remove the x:Name="biggerTextStyle" attribute from the Style declaration, so that the XAML looks like this:

<Style TargetType="Button">
<Setter Property="FontSize" Value="18"/>
</Style>

By removing the x:Name attribute, we create an anonymous style, or a default style, that applies to all the Button controls in our application. Now, our XAML markup looks nice and tidy:

 

<Button Content="Home" />
<Button Content="Gallery" />
<Button Content="Order"/>
<Button Content="Locations"/>
<Button Content="Contact Us"/>
<Button Content="Franchise Opportunities"/>

Overriding an anonymous style
If you want to override an anonymous style and revert to the control's default appearance, set the Style attribute to null using this code: Style="{x:Null}"

Enough of the theory, let's create a default style now!

Time for action – adding the style

Now it's time to create a Style in XAML and tell all the buttons in our project to use that style. This will make all of the buttons have a common text size. You will need to do the following:

  1. Go back to the CakeNavigationButtons project in Visual Studio.
  2. Open the MainPage.XAML file.
  3. Edit the XAML so that it looks like this:
  4. <UserControl x:Class="CakeNavigationButtons.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
    presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-
    compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
    <Style TargetType="Button">
    <Setter Property="FontSize" Value="18"/>
    </Style>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
    <StackPanel>
    <Button Content="Home" />
    <Button Content="Gallery" />
    <Button Content="Order"/>
    <Button Content="Locations"/>
    <Button Content="Contact Us"/>
    <Button Content="Franchise Opportunities"/>
    </StackPanel>
    </Grid>
    </UserControl>

  5. Run the solution and you'll notice that the text on every button is larger.
  6. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  7. Stop the project and return to the MainPage.XAML file.
  8. Change the FontSize to 9.
  9. Add another Setter node to the style:
  10. <Setter Property="Background" Value="Red"/>
  11. Run the project again and you'll see that the font is much smaller and the buttons have taken on a red tone:

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

What just happened?

We just created a Style and added it to our navigation application. Then we referenced the Style using a Markup Extension in the Style property of the button. We then modified the Style, which changed all the controls that referenced it. This should give you a little taste of the power of using Styles in Silverlight.

You may be thinking that editing styles "by hand" can get tedious if we try to do anything more complex, and you're right! Hand editing XAML can only get you so far. Now we'll take our design to the next level by using Expression Blend.

Summary

In this article, we looked at:

  • Using container controls
  • Using styles to customize the look of a control

If you have read this article you may be interested to view :

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide Build enterprise-ready business applications with Microsoft Silverlight 4 with this book and eBook
Published: April 2010
eBook Price: $32.99
Book Price: $54.99
See more
Select your format and quantity:

About the Author :


Frank LaVigne

Frank LaVigne has been hooked on software development since he was 12, when he got his own Commodore 64 computer. Since then, he's worked as developer for fi nancial fi rms on Wall Street and also in Europe. He has worked on various Tablet PC soluti ons and on building advanced user experiences in Silverlight and WPF. He lives in the suburbs of Washington, DC. He founded the CapArea.NET User Group Silverlight Special Interest Group and has been recognized by Microsoft as a Tablet PC MVP. He blogs regularly at www.FranksWorld.com.

 

Books From Packt


Microsoft Silverlight 4 Data and Services Cookbook
Microsoft Silverlight 4 Data and Services Cookbook

3D Game Development with Microsoft Silverlight 3: Beginner's Guide
3D Game Development with Microsoft Silverlight 3: Beginner's Guide

Joomla! 1.5: Beginner's Guide
Joomla! 1.5: Beginner's Guide

OpenX Ad Server: Beginner's Guide
OpenX Ad Server: Beginner's Guide

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

Grok 1.0 Web Development
Grok 1.0 Web Development

SketchUp 7.1 for Architectural Visualization: Beginner's Guide
SketchUp 7.1 for Architectural Visualization: Beginner's Guide

Blender 3D 2.49 Incredible Machines
Blender 3D 2.49 Incredible Machines


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software