Home >
Where the Wild Things Are: an Adventure in Silverlight (Act I)
Credit: A big thank you to Jose Fajardo from Cynergy Systems for his Silverlight expertise (and patience).
Late last year, I took it upon myself to learn Silverlight. You see, I'm both a Flex and a .NET developer, so it makes a certain sense. I've also spent plenty of time criticising fanboys of both genres, so here I am putting my money where my mouth is.
It seems to me that there is a big culture of misinformation in both the Flex and Silverlight camps regarding how the other gets the job done. I figured the best way to bridge the divide was to investigate how Silverlight, and XAML, does the RIA thang. Through this article, I will focus on Flex 4 and Silverlight 3. That is, Flex 4 Beta 2 (Gumbo), Flash Builder 4 Beta 2, Flash Catalyst Beta 2, Silverlight 3 and Blend 3.
Silverlight 4 is on the way, with the Beta announced in Nov 2009. However, I opted not to focus on it in these articles, partially because the release cycle of Silverlight is so fast - I'm not certain how many more changes will come with the final release of Silverlight 4 (and particularly Blend 4).
Read the official release: http://silverlight.net/getstarted/silverlight-4-beta/
Now, I can't spend much time introducing .NET, so I need to assume that you know a little bit about the framework. If you don't, well, there's always Wikipedia. Essentially .NET is Microsoft's object-oriented framework, which - like Java - runs managed code in a virtual machine. Unlike Java, it's restricted to the Windows platform, with the exception of Silverlight.
Act I: Donning the wolf suit
This first in this four part series will cover the elementary aspects of Silverlight - the tooling, the markup, code-behind, componentry and layout.

The Silverlight / WPF Conundrum
When approaching Silverlight, one must brace themselves for the WPF differential. That is, how Silverlight relates to its big brother, Windows Presentation Foundation (WPF). WPF shipped with .NET 3.0 and is essentially the framework that allows .NET developers to write rich Windows applications - the natural successor to Windows Forms. WPF applications can leverage the entire .NET framework and do virtually anything you want on a Windows machine. Silverlight on the other hand, built to be a lightweight, cross-platform and seamless client install, only uses a refactored subset of the .NET Base Class Library (BCL).
It can be a bit of a minefield, trying to learn the differences between both as not only does Silverlight have a fraction of WPF's controls (albeit the better ones), but also best practices have arisen in Silverlight that circumvent the triggering system that WPF boasts. A thorough 70 page whitepaper has recently been circulated that helps bridge the gap.
Nevertheless, Microsoft is striving to bring the two sibling technologies together, and the closer these are the more likely developers will embrace them.
Tooling
One of Silverlight's strengths is the tooling that supports it. First off there's Visual Studio (VS), hands down one of the best IDEs around. Then there's Blend, part of Expression Studio Suite, Microsoft's foray into the designer world that Adobe is champion of. Blend is kind of like a blending [groan] of the Flash authoring tool, Illustrator and Dreamweaver. However, it holds its own with features such as storyboard recording, data binding and state management.
While Blend and VS are interchangeable with both Silverlight and WPF projects, each have their vices and virtues. Blend is primarily for XAML work, whilst Visual Studio is tailored to code behind, execution and debugging. Thankfully, you can roundtrip your project between the two products seamlessly - though it can be irritating constantly switching tools.
The last iteration of Blend was fairly limited, it didn't even have Intellisense (inline documentation) in XAML (at least not natively - even the add-in for 2.5 was for WPF not Silverlight) and if you didn't have VS or equivalent installed, C# files opened in Notepad! (Basically you needed VS to do anything useful). Microsoft however has been working hard to bring Blend up to scratch. Blend 3 now sports VS features such editable code behind and Intellisense support, though it still lacks native debugging.
Blend does take some getting used to, and it certainly didn't appeal to me on first inspection. However, once I got through my initial apprehension, I found it was quite well thought out. The way it handles styles and templates (covered later in the series), is quite impressive. Interestingly, Blend is actually a WPF application itself - a cute touch from Microsoft. I initially found the SketchFlow addition in Blend 3 surprising, though I've come round to see its usefulness - conceptualising RIAs in low fidelity is becoming increasingly relevant. It's even better when you can use those wireframes to generate a project skeleton.
Nevertheless, Flash (& Flex) Builder is not without its virtues. One handy thing is the system wide code hinting. As all Flex devs are aware, the entire Flex/Flash/AIR framework is always available and Builder adds the import statements seamlessly. In Visual Studio and Blend, the Intellisense can't pinpoint classes from the entire .NET library just from the name - the framework is simply too big. You're stuck with Google & MSDN (the Microsoft Developer Network that hosts the full .NET API docs) to know which package to import in your C# files. Furthermore, if you've just written your own user control (like an MXML component) or custom component, you'll need to compile the app first for the system to find it - and then pull it from the Asset manager in Blend - which is cumbersome. It's an improvement from Blend 2, but it's got a way to go.
- Both Blend 3 and Visual Studio 2010 Beta are available as trial downloads.
- Visual Web Developer 2008 Express (a lighter version of VS) is a free product.
Markup
Silverlight and WPF use XAML (eXtensible Application Markup Language) and it serves the same purpose as MXML, more or less. Both MXML and XAML are used to visually represent data structures that will be parsed and translated into code. Just like MXML, you can circumnavigate XAML altogether and write your entire Silverlight solution in C# if you so chose.
XAML is verbose, no doubt about it, and this certainly raises the bar to entry. To be fair though, XAML has a tough job satisfying the draconian .NET, whilst accommodating a demanding Blend. However I'd argue that what it loses in brevity it makes up for in granularity.
Take a look at this example:
Ex. 1: Simple XAML example
<UserControl
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"
x:Class="JustinJMoses.Examples.Silverlight.XAMLExample.MainPage"
Width="640" Height="480" mc:Ignorable="d">
<UserControl.Resources>
<Style x:Key="MyButton" TargetType="Button">
<Setter Property="FontWeight" Value="Bold" />
</Style>
<Style x:Key="WhiteCircle" TargetType="Ellipse">
<Setter Property="Fill">
<Setter.Value>
<SolidColorBrush Color="white" />
</Setter.Value>
</Setter>
<Setter Property="Stroke">
<Setter.Value>
<SolidColorBrush Color="Black" />
</Setter.Value>
</Setter>
<Setter Property="StrokeThickness" Value="7" />
</Style>
<Storyboard x:Name="BeginSpin ">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="ellipse" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)">
<EasingDoubleKeyFrame KeyTime="00:00:02.7000000" Value="307.729"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="3*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Ellipse x:Name="BlackEllipse" Fill="#FF2E0909" Stroke="Black" Margin="50" Grid.Row="0" />
<Ellipse x:Name="OrangeEllipse" Margin="100" Grid.Row="0">
<Ellipse.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFE83535" Offset="0"/>
<GradientStop Color="#FFF4D615" Offset="1"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse x:Name="WhiteEllipse" Margin="150" Style="{StaticResource WhiteCircle}" RenderTransformOrigin="0.5,0.5" >
<Ellipse.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="128.944"/>
<TranslateTransform/>
</TransformGroup>
</Ellipse.RenderTransform>
</Ellipse>
<Button Style="{StaticResource MyButton}" Margin="10" Content="Button" Grid.Row="1" Click="OnClick"/>
</Grid>
</UserControl>
- Styles
- A style setting for a button
- A style setting for an ellipse
- Animations
- A storyboard that rotates the white ellipse ~ 180 degrees
- Grid container with 2 rows
- Three ellipses in the first row
- The first is simply black and set to a margin of 50 around the cell
- The second is filled with a gradient and set to a margin of 100 around the cell
- The third which is styled via a styling control and transformed via an angle of 128 degrees.
- A button in the second row
- Styled to have bold font
- Three ellipses in the first row
Don't Panic
Before you become alarmed with the amount of XAML there is, you first must understand that the above was created within a few minutes in Blend. For us pre-Gumbo Flex devs, we see all that markup and cringe - knowing we'd typically end up doing it all by hand. However with the advent of Flash Catalyst and skinning in Flex 4, it seems Flex too has accepted the idiom shift.
As for the XAML itself, you should be able to see both some striking similarities and differences between it and MXML. In the root tag, you'll notice the xml namespace references just like in MXML. The curly brace syntax looks familiar at first glance, but that's a markup extension, not data binding (both covered later in the series). And what about those property accessors (Grid.Row) as attributes? (these are called attached properties, and they are discussed later in the series). See that whole x:Name thing on the Grid? Well, it performs the identifier role (ie. it's like the id attribute in Flex) - and confusingly you often don't require the namespace prefix (x:), most controls support the Name property.
Did you notice the native use of drawing primitives such as shapes, brushes and fills? Yes, virtually the same ones that Flex has just got around to including in Gumbo. Also notice the white ellipse, and how it's been rotated with a nice render transformation. For all of its verbosity, XAML certainly does seem to provide a lot of fine grained control.
Code
.NET, from its inception, has allowed developers to code in a number of programming languages, and Silverlight is no exception. That said, I'll stick with C# here because I abhor VB - it still conjures up images of the Boogie Man for me. If you understand Java, you'll get C#, though recent iterations of the language are making it a veritable fruit salad of syntax.
C# is beautiful, but it's not for the faint hearted. Actionscript allows you to throw around classes and functions as variables, whereas in C# you'll resort to types and delegates to get the job done. There's too much to cover here, but at the very least I recommend you check out LINQ (I touch on it later in the series) - it really is quite stunning.
One thing you'll notice very quickly with Silverlight is the absence of Script tags in the XAML. In Silverlight, all code must reside in code-behind files. However, there are examples of pseudo-code in XAML, such as markup extensions - curly brace syntax used for referencing other objects and data binding - and even visual code structures, such as triggers (primarily WPF) and behaviours (touched on later in the series).
Ex. 3: Simple HelloWorld application in Silverlight
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace JustinJMoses.Examples.Silverlight.SL_HelloWorld
{
public partial class MainPage : UserControl
{
private int _counter;
//completely irrelevant Property
public int Counter
{
get
{
return _counter;
}
set
{
_counter = value;
}
}
public MainPage()
{
// Required to initialize variables
InitializeComponent();
}
private void OnClick(object sender, System.Windows.RoutedEventArgs e)
{
TextBlock textBlock = new TextBlock();
textBlock.Text = "Hello Homer, this is God.";
LayoutRoot.Children.Add(textBlock);
}
}
}
As you can see, syntactically it's not really that different from Actionscript 3 (AS3). It has all the usual features of an OO language - constructors, interfaces, property accessors - along with abstract classes which AS3 is still missing. Picking up C# should be a piece of cake; learning the .NET framework and XAML is a whole different story.
Componentry
Silverlight and WPF share one thing, and it's their love of the Grid control. Grid - a world apart from its Flex counterpart - is like a super HTML table. Its role is to take up as much space as it can, and allow its children to arrange themselves into its cells as they see fit. It makes much of attached properties, providing programmatic flexibility over where each child component should go.
Ex. 4: Simple Grid in XAML
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SL_HelloWorld.MainPage"
Width="640" Height="480">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Rectangle Fill="#FF94F60E" Stroke="Black"/>
<Ellipse Fill="#FF16C9FC" Stroke="Black" Grid.Column="1" Grid.Row="1"/>
<Button Grid.Column="2" Grid.Row="2" Content="Button This" />
</Grid>
</UserControl>
Notice how the shapes/button automatically size themselves inside the cells, and how the columns/rows can use the star (*) notation to donate relative size. As with the green rectangle, if no row or column is supplied, the first of both is assumed.
Canvas makes an appearance in Silverlight too, very much like its counterpart in Flex. Like VBox and HBox in Flex? StackPanel performs the role of the Flex Box control. Need scrolling or bordering? Simply surround a component with a ScrollViewer or a Border. Sound familiar? Gumbo has taken on the idea of the wrapping scroller - removing the default functionality from components. DataGrid even has an appearance; not part of the core framework, however it's fairly trivial adding it in.
Ex. 5: Wrappable borders in Silverlight
<Border HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="Black" BorderThickness="5" CornerRadius="5">
<Border BorderBrush="Lime" BorderThickness="3">
<Button Height="50" HorizontalAlignment="Center" VerticalAlignment="Top" Width="162" Content="Button"/>
</Border>
</Border>
Layout
The layout of a control in Silverlight depends very much on its container. A control inside a Grid cell will use all the space it can by default.
Ex. 6: Grid with a Button
The button is expanding to use the entire cell.
<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Button"/>
</Grid>
Whereas a control inside a vertical StackPanel will use the minimum amount of vertical space, but the total amount of horizontal space.
Ex. 7: StackPanel (vertical) with a Button
The button expands horizontally, but uses the minimum amount of vertical space)
<StackPanel Orientation="Vertical">
<Button Content="Button"/>
</StackPanel>
Silverlight (and WPF) takes a novel approach to alignment. There are no percentage based widths or heights. What you're seeing above is “stretch” alignment. The control is, by default, stretching to fill the space allocated to its parent. If you wanted the first example to be constrained by its own width and height, you could align it to the appropriate alignment settings.
Ex. 8: Button in a Grid with alignment
The button is horizontally centred and vertically lowered, thereby restricting its size to its content.
<Grid>
<Button Content="Button" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
</Grid>
Now, that's not the end of the story. Of course, you could explicitly set the height or width of the control. Alternatively, there is the Margin property. This dictates how far from the four bounds the control should be, and in combination with the appropriate alignments, can mimic the verticalCenter and horizontalCenter properties of Flex.
Ex. 9: Button in a Grid with margin and alignment
The button is horizontally centred and vertically raised, and offsets to these bound are provided with the margin property.
<Grid>
<Button Content="Button" HorizontalAlignment="center" VerticalAlignment="Top" Margin="25,8,0,0" />
</Grid>
Note
Margin, or Thickness as it is referred to in code, is represented either as a single number or in LTRB. So unlike CSS, (25,8,0,0) is 25 left, 8 top, 0 right, 0 bottom.
Journal Notes
So what can we take away from all this?
- Silverlight and WPF
Silverlight is closely related to WPF but they aren't the same thing. Silverlight is a compact, cross-platform implementation of rich client architecture. WPF is rich desktop application technology, limited to the Windows platform. Microsoft is working at bringing a lot of the features in line but for the time being, developers need to be on the lookout for pitfalls when skirting between the two. Best practises in Silverlight do not equate to best practises in WPF and vice versa. - Tooling
Blend and Visual Studio make a powerful combination. Both tools can work on Silverlight projects and both have their strengths - Blend's is XAML, Visual Studio's is code and debugging. However, unlike Builder in the Flex world, no single tool is Silverlight is currently sufficient for the development lifecycle, though Blend with debugging support would be a worthy adversary. - XAML verbose but fine grained
XAML is no walk in the park, but it's consistent and well designed. The tooling can create a lot of code for small gain; however it does allow you to go in a tweak to your heart's content. - Familiar environment with C#
Syntactically, C# isn't much different from AS3 and Java. However, understanding the .NET framework can be a daunting task. Luckily, (or not, depending on your perspective) Silverlight only uses a small subset of the .NET framework, lowering the barrier to entry. - Good support for graphic primitives
XAML and Silverlight support graphic primitives natively, such as shapes, paths and brushes. These graphics are well supported in Blend. - Componentry and layout can be confusing
It takes a while to get your head around some of the components in Silverlight. This includes wrapping controls with borders and scrolling, using margin and alignments, and even content controls thrown in the mix (covered later in the series). If you couple that with the idiosyncrasies of each container, and the monolithic Grid control, a Flex developer can find themselves in a world of hurt pretty quickly. However, like any skill, once you familiarise yourself with it, the Silverlight idiom becomes second nature.
Stay tuned for Act II where we delve a little deeper into the world of Silverlight.











Facebook Application Development
WoW, what a great post. I am a Flex/.NET myself and find that there are few of us around. Haven't tried SL since 2.0 beta, been itching to give SL4 a shot to see where the 2 camps are at. Very interested in followup posts.
I must admit the thought of SL seriously makes me think twice about my future with Flex. Seems like SL is moving at 4x the speed of Flex, add to that all the 3rd party support which Adobe doesn't seem to care for and SL will be a monster in 2 years time.
Very nice write up, good to see an agnostic RIA technologist taking the time to understand the tools available. Would be interested in your views on capabilities, applicability, performance and demand between the two platforms in your experience.
Frank Nimphius and Jobinesh Purushothaman is coming to Bangalore this April at Great Indian Developer Summit 2010 ( developersumit dot com) to to show how JavaServer Faces can be used to build compelling Ajax user interfaces for Web Services models giving end users a comfortable working environment that includes client side validation and user interface customization.
@Tom, thank you. Whilst Silverlight is moving at exceptional speed, the groundwork that Flex has laid in the RIA space is huge.
Even after writing this series, I still find that Flex provides a certain level of comfort and flexibility (groan) that I just don't get with Silverlight. But, each to their own.
@DannyT
* Capabilities - I've covered a fair chunk of Silverlight in this series, and I think for the most part, the two are on par. For example, SL is geared up nicely to use the same codebase with RIA services, and Flex has countered with streamlined remoting in Flash Builder.
* Applicability - Right now, the decision between the two platforms comes down to a question of what dev team you have. If you're a .NET house, you'll go SL, an open-source or LAMP team will likely choose Flex.
One bonus of using Flex is being able to leverage designers who already have Flash/Illustrator skills. MS have tried to catch up with the "Import from Illustrator/Photoshop" addition in Blend but still need to get designers using Expression. Honestly, the biggest hurdle I've seen for takeup of SL seems to be a lack of talented designers.
* Performance - honestly, I'm no expert on this - although I've seen a few write ups out there.
* Demand - well, this is the kicker, aint it? I mean, obviously MS are pushing the SL platform, but, as a user, I only really see it appear on sites where the development is .NET centric (Coastalwatch webcams here in Australia is a good example). You hear around dev circles (non-Flex) that Silverlight is going to destroy Flash, but honestly I think it's a misinformed opinion. It comes from a typical developer's inane fear of Flash. Most of them (like me), dabbled with Flash in the past and found it a veritable minefield (coding in layers and 4D is a feat). They are generally ignorant about Flex, and think we're still using Flash Pro to make our RIAs :)
I think for SL to generate demand, it needs to keep proving itself to users in areas that Flash can't yet go (Deep Zoom comes to mind).
@Justin
I agree that finding Silverlight designer is not a easy task. From my experience I recruit Flash designers (there are plenty) and train the designer to take Adobe Illustrator work, then import into Blend and there is always need for the designer to go back to Blend and tweak as the import is not always perfect; the task can get very tedious. Hardest thing about recruiting Flash designer often is the Flash designer loves Flash. But I am finding that slowly lots of designers are looking into Silverlight because of mass marketing Microsoft is doing (i.e. UFC, Olympic, NBC ect...). I expect Microsoft to spend lots of money promoting and integrating Silverlight to big companies and taking good chunk of market share away from Flash.
Personally, I think this is golden age for the designers as their demand wil increase in both Flash and Silverlight community and any designers who has both skill will certainly benefit in this down economy.
Nice post about Silverlight and Flex! I am a Microsoft trainer as well as an Adobe trainer and I think you'd like my posts comparing Silverlight 4 and Flex 4 on a feature level. You can find them here:
http://blogs.infosupport.com/blogs/alexb
I'm eagerly awaiting your next posts :)
@NewAgeSolution agreed.
@Alex, nice blog! It's ambitious trying to compare features in the two blow-by-blow (I should know :P). I particularly like your data validation post and how you mention it blew out so quickly :)
Conumdrums are great mind twisters aren't they! you need a mobile mind to see through it all.