Silverlight is supported by all major browsers on both Mac OS X and Windows, and with Moonlight on Linux as well. Particular care is being taken to account for differences in platform and browser capabilities to ensure a consistent experience including experiences on Internet Explorer 6, 7, 8, Firefox 2 and 3, Safari 3 and 4, and now Google Chrome.
Of course your next web app can be built just fine without Silverlight. And yes, of course, you could watch Avatar in 2D. But it wouldn’t be as much fun and it wouldn’t look half as good. That - in a nutshell – may be the biggest of the many reasons (see below) that your next web application should seriously consider using Silverlight.
Efficient integration with existing desktop applications is just another reason that Silverlight doesn’t just limit you to doing 'web’ stuff. Silverlight offers options to securely interact with desktop files, devices, data and applications such as Microsoft Office. Existing Web and SharePoint sites can be enhanced by incrementally adding Silverlight components.
Built on Microsoft .NET - Microsoft’s industrial-strength application development tools and a platform that promotes stability, scalability, reliability, and performance.
Cross platform: Current silverlight plugins exist for all major browsers on Mac, Windows and Linux as well as mobile devices such as Windows Phone 7, Nokia Series 60 and set-top boxes.
Client (and Server) Agnostic - Silverlight is both client and server agnostic. There's no difference between the Macintosh and PC runtimes; you don't need any Microsoft software on the server if you don't want to - you can deliver a great Silverlight experience from an Apache / Linux server to a Mac OS 10 client.
Silverlight 4.0 Features
Silverlight 4 delivers a full suite of powerful features to application developers, bringing innovative platform capabilities to browser-based experiences. Silverlight provides an ideal platform for developing and deploying modern business applications for both internal and end-user applications on both sides of the firewall
- Enabling business application development. Silverlight 4 affirms its position as the natural choice for building business applications on the Web:
What’s new for application developers
- Comprehensive printing support now enables the creation of a virtual print view, enabling applications to deliver print-friendly documents.
- A full set of controls with more than 60 customizable, skinnable components makes it easy to build forms that can be sorted, resized and validated. New controls include RichTextArea with hyperlinks, images and editing.
- Localization enhancements with bidirectional text, right-to-left support and complex scripts such as Arabic, Hebrew and Thai and 30 new languages.
- The Microsoft .NET Framework Common Language Runtime (CLR) now enables the same compiled code to be run both on the server and the client, reducing development time and testing resources.
- Enhanced databinding support reduces the amount of code needed to work with customized data for display.
- Managed Extensibility Framework supports building completely modular applications, allowing for fast startup and download, efficient development and testing, as well as agile customization and servicing.
- Windows Communication Foundation RIA Services introduces enterprise class networking and data access, allowing applications to work with any source of data and any server.
- Extensive tooling support for Silverlight, new in Visual Studio 2010:
- Fully editable design surface for drawing out controls and layouts
- Rich property grid and new editors for values
- Drag and drop support for databinding and automatically creating bound controls such as listbox and datagrid
- New datasources window and picker
- Easy-to-pick styles and resources to make a good-looking application based on designer resources built in Expression Blend
- Built-in project support for Silverlight applications
- Editor with full IntelliSense for XAML and C# and Visual Basic languages
- Empowering richer experiences. Silverlight 4 introduces additional capabilities that enable developers to create richer, more appealing, high-performance interactive and innovative media experiences:
- Enhanced animation capabilities allow for more dynamic, interactive presentation of data in lists.
- Webcam and microphone support allow sharing of video and audio in applications such as chat and customer service.
- Audio and video local recording capabilities capture RAW video without requiring server interaction, allowing new scenarios such as capturing voice or video to send in e-mail, or allowing the recording to be edited locally before saving.
- Copy/paste and drag-and-drop make it easy to bring photos, text and other data into your application.
- New features such as right-click and mouse wheel scrolling enable developers to add conventional desktop interaction models.
- Silverlight 4 runs across all platforms and major browsers.
- Silverlight 4 applications start quicker and run 200 percent faster than the equivalent Silverlight 3 applications with performance optimizations.
- Multitouch support enables a range of gestures and touch interactions to be integrated into user experiences.
- Multicast networking enables enterprises to lower the cost of streaming broadcast events such as company meetings and training, with seamless interoperability with existing Windows Media Services streaming infrastructure.
- Content protection now available for H.264 media through Silverlight DRM powered by PlayReady.
- Output protection for audio/video streams allowing content owners or distributors to ensure protected content is only viewed through a secure video connection.
- Official support of the Google Chrome browser
- Hardware acceleration for Deep Zoom
- XAP signing and verification to ensure application integrity
Moving beyond the browser. Silverlight 4 extends out-of-browser capabilities pioneered in Silverlight 3 that enable a Web presence to establish closer, more persistent relationships with customers without any additional runtime download or the need to write applications in a different way.
For sandboxed applications
-
- Developers can place HTML within their application, enabling much tighter integration with content from Web servers such as e-mail, help and reports.
- Silverlight 4 provides support for desktop pop-up notification windows to easily provide real-time information and feedback to users using a common user interface metaphor.
- Offline DRM extends the existing Silverlight DRM powered by PlayReady technology to work in a disconnected state, enabling users to view content and engage with a Silverlight application where and when they want. Protected content can be delivered with an embedded license so that users can go offline immediately and start enjoying their content.
- Silverlight 4 offers full control over window settings such as start position and size to ensure applications have maximum usability and flexibility.
For trusted applications
-
- Users can read and write files to their My Documents, My Music, My Pictures and My Videos folder (or equivalent for non-Windows platforms), enabling applications to make local copies of reports and media files.
- COM automation enables access to devices and other system capabilities such as a Universal Serial Bus security card reader.
- Users can access other desktop programs such as Microsoft Office Excel to create a report.
- Group policy objects allow organizations to manage which applications are trusted.
- Comprehensive keyboard support in full-screen out-of-browser mode enhances kiosk and media applications.
- Enhancements to networking allow cross-domain access without a security policy file.
How is Silverlight different from WPF?
Silverlight and WPF Architectural Overview
Windows Presentation Foundation (WPF) provides developers with a unified programming model for building rich Windows Forms applications that incorporate user interface (UI), media, and documents. WPF enables software developers to deliver a new level of "user experience" (UX) by providing a declarative-based language (XAML) for specifying vector-based graphics that can scale and take advantage of hardware acceleration.
Silverlight is a cross-browser, cross-platform implementation of the .NET Framework for delivering next-generation rich interactive media and content over the Web and for developing browser-hosted Rich Internet Applications (RIAs) that can integrate data and services from many sources. Silverlight enables developers to build applications that significantly enhance the typical end user experience, compared with traditional Web applications. Like WPF, Silverlight provides a XAML-based language to specify user interfaces.
Silverlight and WPF share many of the same features and capabilities, but they are built on top of different run-time stacks, as illustrated in Figure 1. WPF leverages the full .NET Framework and executes on the common language runtime (CLR). Silverlight is based on a subset of XAML and the full .NET Framework, and it executes on a browser-hosted version of the CLR.
For more information about WPF architecture, see WPF Architecture on MSDN. For more information about Silverlight architecture,
see Silverlight Architecture on MSDN.
Differences Between Silverlight and WPF
To keep Silverlight small and lightweight, some WPF and .NET Framework features are not available in Silverlight. Because of this, there can be subtle— and not so subtle—differences that have to be carefully considered when moving an application between Silverlight and WPF or when building an application that targets both WPF and Silverlight. For a summary of these differences, see WPF Compatibility on MSDN.
This section describes some of the major differences the patterns & practices team encountered during the development of the Composite Application Guidance for WPF and Silverlight.
Resources – How are they different in Silverlight?
Resources are simple collections of key-value pairs that can store almost any element (strings, brushes, styles, data sources, and many others). Resources can be associated with almost any element class that exposes a Resources property of type ResourceDictionary. The following are the main differences between Silverlight and WPF concerning resources:
- Resources can contain static or dynamic content. Dynamic content can be changed at any time and consumers of the resource will be automatically updated. Dynamic resource references are not supported in Silverlight; therefore, only static resource references are available.
- Merged dictionaries are useful for separating resources so that they can be shared within the application as if they were in a single logical location. Silverlight does not currently support MergedDictionaries. Global resources can be defined in the App.xaml file or locally in each user control that will use the resource.
Styles – How do they differ between Silverlight and WPF?
There are several differences between Silverlight and WPF when using styles. You should be aware of the following limitations in Silverlight:
- After you set a style to a FrameworkElement at run time, it cannot be subsequently changed.
- Style inheritance is not supported, because the BasedOn property is not available.
- Silverlight does not support implicit styles applied using the TargetType attribute value. If you define an application-level style for a specific user control, it will not be automatically applied to all instances of the user control; instead, you must explicitly reference the style by its key for each control instance.
WPF Triggers – Are they available in Silverlight?
Triggers allow designers to define the visual behavior of a control by declaratively specifying how its properties change in response to events or property changes, such as highlighting a button when it is clicked. Typically, triggers are fired when a property of a control changes and results in one or more other properties of that control also changing. Triggers are defined inside a style and can be applied to any object of the specified target type.
Silverlight does not support triggers in Styles, ControlTemplates, or DataTemplates (the Triggers collection does not exist on these elements). However, similar behavior can be achieved by using the Silverlight Visual State Manager (VSM) to define interactive control templates. Using VSM, the visual behavior of a control, including any animations and transitions, are defined in the control template. This can be easily done by using Blend 2.5. However, be aware that the XAML file will get more complex and that control templates built for Silverlight are not yet compatible with WPF.
For more information about the Visual State Manager, see Creating a Control That Has a Customizable Appearance on MSDN.
Data Binding differences between WPF and Silverlight
Both WPF and Silverlight provide data binding support. The following are the main differences between Silverlight and WPF data binding:
- In Silverlight, there is no support for the ElementName property in the binding syntax, so the property of a control cannot be bound to a property in another control. In addition, Silverlight does not support the RelativeSource property, which is useful when the binding is specified in a ControlTemplate or a Style.
- In Silverlight, there is no OneWayToSource data flow mode.
- In Silverlight, there is no UpdateSourceTrigger property. All updates to the source in the two-way binding mode occur immediately, except in the case of TextBox, in which case changes are propagated to the source when the focus is lost.
- In Silverlight, you cannot bind directly to XML data. A possible workaround for this is to convert the XML to CLR objects, and then bind to the CLR object.
- In Silverlight, there is no XMLDataProvider class.
- In Silverlight, there is no support for binding validation rules. Controls in Silverlight can be configured to raise an event to indicate that a validation error has occurred.
- In Silverlight, there is no ReadOnlyObservableCollection; however, ObservableCollection is supported. ReadOnlyObservableCollection is a read-only wrapper around the ObservableCollection. The ObservableCollection represents a dynamic data collection that provides notifications when items get added, removed, or when the whole collection gets refreshed.
- In Silverlight, there is no CollectionView class. In WPF, this class represents a view for grouping, sorting, filtering, and navigating a data collection. The ICollectionView interface is available in Silverlight; by using this, developers can create their own CollectionView implementations, although most Silverlight controls do not automatically interact with this interface.
- In Silverlight, there is no DataTemplateSelector class. In WPF, this class provides a way to choose a DataTemplate based on the data object and the data-bound element.
Commanding – Routed Commands – How do they differ in Silverlight?
The following are the differences between Silverlight and WPF regarding commanding:
- Routed commands are not available in Silverlight. However, the ICommand interface is available in Silverlight, allowing developers to create their own custom commands. The Composite Application Library provides the DelegateCommand and CompositeCommand classes to simplify command implementation. For more information, see the Commands technical concept.
- In WPF, controls can be hooked up to commands through their Command property. By doing this, developers can declaratively associate controls and commands. This also means a control can interact with a command so that it can invoke the command and have its enabled status automatically updated. Silverlight controls do not currently support the Command property. To help work around this issue, the Composite Application Library provides an attached property-based extensibility mechanism that allows commands and controls to be declaratively associated with each other. For more information, see "Using Commands in Silverlight Commands" in the Commands technical concept.
- There is no input gesture or input binding support in Silverlight.
Miscellaneous
The following are some miscellaneous differences between Silverlight and WPF:
- In Silverlight, the UIElement class has an internal constructor; therefore, you cannot create a control inheriting from it.
- In Silverlight, there is no x:type markup extension support or support for custom markup extensions.
- In Silverlight, items added to a TabControl control are not automatically wrapped inside a TabItem type, as is the case with WPF.
Getting Starting With Silverlight (Hello World)
Installing the Development Tools
Creating Silverlight applications can all be done with a very basic editor, such as notepad, but it's much easier, faster, and productive to use development tools specifically designed for creating Silverlight applications. The tools you'll need for this QuickStart are a version of Microsoft Visual Studio 2010 (the Microsoft Visual Web Developer 2010 Express version is free) and the Silverlight 4 Tools for Visual Studio 2010.
Another tool you may find useful is Microsoft Expression Blend, which is a powerful WYSIWYG design tool, though we will not be using Blend in this example.
Creating Your First Application
The first thing we need to do is start Visual Studio and create a new project. After you've started Visual Studio, choose the "New Project" menu option: File->New->Project
This will bring up the New Project dialog. In the Template list on the left, select Visual C# (Visual Basic is also available) and then Silverlight. Then select Silverlight Application as the project type. Now name your project HelloWorld and select OK.
The next dialog box that opens asks if you want to create a new Web Site or simply use a test page. For this sample, unselect "Host the Silverlight application in a new Web site". We will use the test page option. When developing Silverlight applications, there are some benefits in using the Web site option, but for this example the test page is sufficient.

That is all there is to creating a new Silverlight project. Next we will add some functionality to the application.
If you don't see the Solution Explorer (typically on the right side of the window) you can open it from View->Solution Explorer. In the Solution Explorer, there are a number of project files. The files we will be using in this QuickStart are MainPage.xaml and MainPage.xaml.cs. If you are unfamiliar with XAML, XAML is an XML based declarative language used to create and layout UI elements. See the XAML QuickStart for more information on XAML.
Double click on MainPage.xaml. This will open the MainPage.xaml file in the main editor window.
We will add a simple TextBlock that displays the message "Hello, World!". Between the <Grid> tags, add a <TextBlock /> element. Now add a Text attribute to the TextBlock element and give it a value of "Hello, World!". Your final XAML should like the XAML in the screenshot below.

Running Your First Application
Now that you have created your first Silverlight application, you need to run it. You could add the application to an existing Web site, but while developing, an easier way to execute your application is by using the debug functionality of Visual Studio. To run a Silverlight application in Debug mode, either choose Debug->Start Debugging or hit F5. This will launch a test Web page that hosts your application. If there are errors compiling your application, Visual Studio will display error information.
To stop debugging, either close the browser window that opened or choose Debug->Stop Debugging.
The following example is our Silverlight application so far.
Hello World
XAML
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="Hello, World!" />
</Grid>
Using Layout Management
Both Silverlight and WPF support a flexible layout management system that enables developers and designers to easily coordinate how controls are positioned within a UI surface. This layout system supports both a fixed position model where controls are positioned using explicit coordinates, as well as a more dynamic position model where layout and controls can be automatically sized and flowed as the browser resizes.
Developers using Silverlight and WPF use layout panels to coordinate the position and resizing of controls contained within them. The built-in layout panels in Silverlight 2 include three of the most commonly used ones in WPF:
Canvas Panel
The Canvas panel is a pretty basic layout panel that supports positioning controls contained within it using explicit coordinates.
Elements can be positioned in a Canvas using a XAML feature called "Attached Properties" - which allow you to specify a control's position relative to its immediate parent Canvas control's Left, Top, Right or Bottom coordinates. Attached properties are useful as they allow a parent panel to extend the property set of a control contained within it. Canvas, by defining an attached property for “Top” and ”Left” basically adds the ability to define left and top attachment on Button (or any other UI element that is added to the Canvas), without any need to actually add a property to the Button class, or modify the Button class in any way.
We could add two buttons to a Canvas container, and position them both 50 pixels from the left of the Canvas, and 50 and 150 pixels from the top using XAML like below (the Canvas.Left and Canvas.Top attributes are examples of the attached property syntax):
<Canvas Background="#FF5C7590" >
<Button Content="Button 1" Width="100" Height="50" Canvas.Left="50" Canvas.Top="50"/>
<Button Content="Button 2" Width="100" Height="50" Canvas.Left="50" Canvas.Top="150"/>
</Canvas>
This would then render our buttons like below:
While the Canvas is useful for scenarios where the UI elements contained within it never move, it tends not to be very flexible as you add more controls into it or handle scenarios where the UI needs to resize or move. In cases like these you end up having to manually write code yourself to move things around inside the Canvas (which is a pain). A better solution for these dynamic scenarios is typically to use an alternative layout panel that has built-in semantics to-do this for you - like the StackPanel and Grid.
StackPanel
The StackPanel control is a simple layout panel that supports positioning its contained controls in either a row or column layout. StackPanels are typically used in scenarios where you want to arrange a small subsection of the UI on your page.
For example, we could use the StackPanel to vertically arrange three buttons on our page using XAML markup like below:
<StackPanel Background="#FF5C7590" >
<Button Content="Button 1" Width="100" Height="50" Margin="10"/>
<Button Content="Button 2" Width="100" Height="50" Margin="10"/>
<Button Content="Button 3" Width="100" Height="50" Margin="10"/>
</StackPanel>
At runtime the StackPanel would then automatically arrange the Button controls in a vertical stack for us like below:
We could alternatively set the "Orientation" property of the StackPanel to be "Horizontal" instead of Vertical (which is the default):
<StackPanel Orientation="Horizontal" Background="#FF5C7590" >
<Button Content="Button 1" Width="100" Height="50" Margin="10"/>
<Button Content="Button 2" Width="100" Height="50" Margin="10"/>
<Button Content="Button 3" Width="100" Height="50" Margin="10"/>
</StackPanel>
This will then cause the StackPanel to automatically arrange the Button controls in a horizontal row like below:
Grid Panel
The Grid control is the most flexible layout panel, and supports arranging controls in multi-row and multi-column layouts. It is conceptually similar to an HTML Table element.
Unlike an HTML Table, you don't embed controls within column and row elements. Instead you specify a Grid's Row and Column definitions using <Grid.RowDefinitions> and <Grid.ColumnDefinitions> properties that are declared immediately under the <Grid> control. You can then use the XAML "Attached Property" syntax on controls contained within the grid to indicate which Grid row and column they should be populated within.
For example, we could declare a Grid layout has three rows and three columns, and then position 4 buttons within it using XAML like below:
<Grid Background="#FF5C7590">
<Grid.RowDefinition>
<RowDefinition Height="60"/>
<RowDefinition Height="60"/>
<RowDefinition Height="60"/>
</Grid.RowDefinition>
<Grid.ColumnDefinition>
<ColumnDefinition Width="110"/>
<ColumnDefinition Width="110"/>
<ColumnDefinition Width="110"/>
</Grid.ColumnDefinition>
<Button Content="Button 1" Width="100" Height="50" Grid.Column="1" Grid.Row="0"/>
<Button Content="Button 2" Width="100" Height="50" Grid.Column="2" Grid.Row="1"/>
<Button Content="Button 3" Width="100" Height="50" Grid.Column="0" Grid.Row="1"/>
<Button Content="Button 4" Width="100" Height="50" Grid.Column="1" Grid.Row="2"/>
</Grid>
The Grid layout panel would then position the Button elements for us like so:
In addition to supporting absolute sizing (for example: Height="60") the Grid's RowDefinition and ColumnDefinition controls also support an AutoSizing mode (Height="Auto"), which automatically sizes the Grid or Row based on the size of the content contained within it (you can also optionally specify maximum and minimum size constraints - which can be very useful).
The Grid's Row and ColumnDefinitions also support a feature called "Proportional Sizing" - which enables the size of a Grid's Rows and Columns to be spaced proportionally relative to each other (for example: you could have the second row grow at 2x the rate of the first one).
You'll find that the Grid provides a ton of power and flexibility - and it will probably be the most common layout panel control you'll end up using.
Data Binding to Controls
While binding can be established using a manual push and pull process, the data binding capabilities of XAML and Silverlight offer more power and flexibility with less runtime code. This provides a more robust data bound user-interface with fewer failure points than with manual binding.
The process of Automated Data-Binding in Silverlight links a UI FrameworkElement to a data source entity and back. The data source entity contains the data that will flow to the FrameworkElement control for presentation. The data can also flow from the control in Silverlight back to the entity. For example, an entity may be bound to a series of controls, each of which is linked to a specific property on the entity, as shown in Figure 1.
The entity is set to the DataContext for a control. This then allows that control, or any child control of that control, to be bound directly to the entity. There are many important players in this process that will be introduced in this article, including the DataContext, binding modes, and dependency properties on FrameworkElement controls. Each of these plays a critical role in customizing how the data binding process operates in a Silverlight application
There are some basic rules to follow when you are setting up data binding in Silverlight. The first rule is that the target element of a data binding operation must be a FrameworkElement. The second rule says that the target property must be a Dependency Property.
Rule #1: FrameworkElement
The target of data binding must be a FrameworkElement. This many sound limiting but it is quite the opposite. The FrameworkElement has many subclasses that inherit from it. Figure 2 shows several controls that inherit from the FrameworkElement. The FrameworkElement extends the UIElement class and adds capabilities that allow it to control layout and support data binding.
Any control that derives from FrameworkElement can be used for layout on a page or user control, and can be involved in data binding as a target. There are other classes that derive from some of the subclasses shown in Figure 2, such as System.Windows.Controls.Textbox, too.
In data binding, both a data source and at least one target are required. The target can be a control or set of controls on a page (or within a user control). Basically, the data can travel in either direction between the source and the target. The sources of data are generally instances of objects such as a domain entity. The properties of the data source are referred to in the targets, so that each target control knows which property of the entity it should be bound to.

Rule #2: Dependency Properties
As mentioned previously, the second rule of data binding in Silverlight is that the target must be a Dependency Property. This might initially seem to be a restriction, especially since one of the first controls people think about when they think of data binding is the TextBox’s Text property. However if you take a look at the source code (using a tool like Lutz Roeder’s .NET Reflector) for the Text property of a TextBox you will see that it too is a Dependency Property. In fact most properties that you can think of are Dependency Properties, which is great, since that means you can use data binding with so many properties.
Dependency Properties are data-bound properties whose value is determined at runtime. The purpose of dependency properties is to provide a way to determine the value of a property based on inputs including, but not limited to, user preferences, resources, styles, or data binding. An example of a Dependency Property can be seen in the XAML code snippet below by looking at the Fill property.
<Rectangle Fill="#FFE5CECE" Grid.Column="0" Grid.Row="0"
RadiusX="20" RadiusY="20" Opacity="0.8" StrokeThickness="0" />
The Rectangle control’s Fill property is a Dependency Property that is set to a specific color, in this case. The Fill property’s value could be determined using a resource or by data binding to an object. This would allow the color of the rectangle to be determined at runtime.
Dependency Properties are not declared as a standard .NET CLR type, but rather they are declared with a backing property of type Dependency Property. The code in Example 1 shows the public facing property Fill and its type Brush However you’ll see that its backing property is not Brush but rather the type Dependency Property. You can always identify a Dependency Property by looking at its backing property’s name. If the backing property name has the Property suffix then it is generally the backing property for a Dependency Property.
public static readonly DependencyProperty FillProperty;
public Brush Fill
{
get { return (Brush) this.GetValue(FillProperty); }
set { base.SetValue(FillProperty, (DependencyObject) value); }
}
Table 1 shows a quick reference of these terms applied to the code in Example
|
Term
|
Description
|
Explanation
|
|
Dependency Property
|
The property named Fill
|
A property that is backed by a field of type Dependency Property
|
|
DependencyProperty
|
The type of FillProperty
|
A type that defines the backing field
|
|
Dependency Property Identifier
|
The instance of the backing property,FillProperty . This is referred to in the CLR Wrapper code with the GetValue and SetValue methods.
|
An instance of the Dependency Property
|
|
CLR Wrapper
|
The setter and getter accessor code for the Fill property.
|
The getter and setter for the property
|
A dependency property can also get its value through a data-binding operation. Instead of setting the value to a specific color or a Brush, the value can be set through data-binding. When using data-binding, the property’s value is determined at runtime from the binding to the data source.
The following XAML example sets the Fill for a Rectangle using data-binding. The binding uses an inherited data context and an instance of an object data source (referred to as MyShape). The binding syntax and the DataContext will be explored later in this article.
<Rectangle Fill="{Binding MyShape.FillColor}" Grid.Column="0" Grid.Row="0"
RadiusX="20" RadiusY="20" Opacity="0.8" StrokeThickness="0" />
Besides basic data binding, styles and templates are a huge beneficiary of using dependency properties. Controls that use styles are indicated through a StaticResource (defined in app.xaml or defined locally). The style resources are often set to a Dependency Property to achieve a more elegant appearance.
Dependency Property values are determined using an order of precedence. For example a style resource may set the Background Dependency Property to White for a canvas control. However the Background color can be overridden in the control itself by setting the Background property to Blue. The order of precedence exists in order to ensure that the values are set in a consistent and predictable manner. The previous example of the Rectangle control shows that the locally-set property value has a higher precedence than a resource.
When creating a binding, a Dependency Property of a FrameworkElement must be assigned to the binding. This is the target of the binding operation. The source of the binding can be assigned through the DataContext property of the UI element or any UI element that is a container for the bound UI element.
Binding XAML Markup Extensions
\One of the main pieces of functionality offered by the Dependency Property is its ability to be data bound. In XAML, the data binding works through a specific markup extension syntax. Alternatively, the binding can be established through .NET code. A set of XAML attributes exist in order to support the data binding features. A basic example of the usage of these extensions is shown in the pseudo-code examples below.
<someFrameworkElement property="{Binding}" .http://www.sample.com/>
<someFrameworkElement property="{Binding Path=pathvalue}" .http://www.sample.com/>
<someFrameworkElement
property="{Binding oneOrMoreBindingProperties}" .http://www.simple-talk.com/>
<someFrameworkElement property="{Binding Path=pathvalue, oneOrMoreBindingProperties}" ,
http://www.sample.com/>
The element must be a FrameworkElement (thus the name someFrameworkElement). The property would be replaced with the name of the property that will be the target of the binding. For example the element might be a TextBox and the property might be Text. To bind the value of the property to a source the binding markup extensions can be used.
The Binding attribute indicates that the value for the Dependency Property will be derived from a data binding operation. The binding gets its source from the DataContext for the element or the DataContext that is inherited from the closest parent element. To bind an element to an object that is the DataContext (and not to a property of the object), all that is needed is the Binding attribute (see the first line of XAML from the previous example). For example, this is usually the case when binding an object that is a list to a ListBox.
The second usage of the binding markup syntax is to specify a pathvalue. This can be the name of a property that exists on the bound object. For example, to bind a TextBox’s Text property to the CompanyName property of an object in the inherited DataContext the following code could be used:
<TextBox x:Name="tbCompany" Text={Binding CompanyName}”/>
Binding Extension Properties
Additionally, there are a handful of other binding properties (referred to in the previous example as oneOrMoreBindingProperties) that can be set with the XAML binding extensions in Silverlight. These properties are:
- Converter
- ConverterCulture
- ConverterParameter
- Mode
- Source
- Path
- NotifyOnValidationError
- ValidatesOnExceptions
The Mode indicates the binding mode that specifies how the binding will operate. Valid values for the Mode property are OneTime, OneWay and TwoWay. An object reference can be set to the Source property. If the Source property is set the object reference will override the DataContext as the data source for this binding. All of these properties are optional. The default value for the Mode is OneWay while if the Source property is omitted the data source will defer to the DataContext.
Keep in mind that a Dependency Property follows an order of precedence to determine its value. If a Dependency Property is bound and in code the property is set to a value explicitly, the binding is removed. For example the tbCompany TextBox in the previous example is bound to the CompanyName property of the DataContext. If the Text property of tbCompany is set to Foo in code, then the binding is removed.
DataContext
The DataContext refers to a source of data that can be bound to a target. The DataContext often is set to an instance of an entity. Once set, the DataContext can be bound to any controls that have access to it. It can be used to bind all controls within a container control to a single data source. This is useful when there are several controls that all use the same binding source. It could become repetitive to indicate the binding source for every control. Instead, the DataContext can be set for the container of the controls.
Each FrameworkElement has a DataContext. This includes the instances of the UserControl class that the examples in this article have demonstrated, since the UserControl class inherits from the Control class which in turn inherits from the FrameworkElement class. This means that, on a single UserControl, there could be objects assigned to dozens of DataContext properties of various FrameworkElement controls. For example the UserControl, a layout control such as a Grid, and a series of interactive controls such as the TextBox, CheckBox and ListBox controls might all have their DataContext property set.
To use the DataContext, the XAML must also be modified using the binding markup extension syntax. The newly modified XAML for the UserControl is shown in the code example below. This code is only the portion of the entire XAML file that shows only the elements where binding takes place.
<TextBox x:Name="tbFirstName" Grid.Column="1" Grid.Row="0" Margin="10,5,10,5" HorizontalAlignment="Left" Height="30"
Width="240" Style="{StaticResource textBoxStyle}" Text="{Binding FirstName}"/>
<TextBox x:Name="tbLastName" Grid.Column="1" Grid.Row="1" Margin="10,5,10,5" HorizontalAlignment="Left" Height="30"
Width="240" Style="{StaticResource textBoxStyle}" Text="{Binding LastName}"/>
<TextBox x:Name="tbCompany" Grid.Column="1" Grid.Row="2" Margin="10,5,10,5" HorizontalAlignment="Left" Height="30"
Width="240" Style="{StaticResource textBoxStyle}" Text="{Binding Company}"/>
This XAML shows that the Text property of each TextBox is bound to a property of the data source. The data source is not listed anywhere in this XAML code. Therefore it is inferred that the Binding will use the DataContext that is closest in the inheritance hierarchy to the Target. If the TextBox itself has its DataContext property set, it will use the object from its own DataContext.
DataContext Binding
private void DataContextBinding_Loaded(object sender, RoutedEventArgs e)
{
person = new Person { FirstName = "Sam", LastName = "John", Company = "Foo Company" };
this.DataContext = person;
}
The code in Example shows the event handler that will execute when the UserControl is loaded. First an instance of the Person class is created and initialized. Then the DataContext property (also a Dependency Property) of the UserControl is set to the person instance.
This gives each TextBox’s Binding a valid DataContext to use as the data source
Data Access from Silverlight Applications
One of the bigger beginner misconceptions about accessing data in Silverlight is people looking for some ADO.NET class library in Silverlight. Stop looking, it isn’t there. Remember, Silverlight is a client technology that is deployed over the Internet. You wouldn’t want a browser plug-in to have direct access to your database…as you’d have to expose your database directly to the web. We all know that is generally a big no-no.
So the next logical step is to expose data via service layers. Silverlight communicates with data using three primary means:
- Web services: SOAP, ASP.NET web services (ASMX), WCF services, POX, REST endpoints
- Sockets: network socket communication
- File: accessing static content via web requests.
Sockets
Sockets are probably the most advanced data access endpoints. These require a socket host to exist and, at the time of this writing, also require communication over a specific port range. If this is acceptable for you, this can be a very efficient and powerful means of communication for your application. Most public facing web applications will not have this option though; the sockets option seems to be more for internal facing business applications. Some resources for learning more about Silverlight and Sockets:
Working with Sockets requires you to really understand your deployment scenario first before you jump right in and think this will be the best method.
File Access
Silverlight can communicate with local data or data on the web. For local data access, the application does not have direct access to the file system, but rather can read/write data via user-initiated actions using the OpenFileDialog and SaveFileDialog APIs to request and save streams of data to the local user’s machine.
Additionally, one can use plain text files or XML files on the web and have your Silverlight application use standard HTTP commands to read/write that information. Here’s some helper information on using some of these methods:
You may find yourselves using these techniques to save settings-based data or use very simple data access.
Web Services
This is the heart of accessing data in Silverlight – by providing a service layer. Silverlight supports accessing standard ASP.NET web services (ASMX) or WCF-based services using the familiar Add Service Reference methods in Visual Studio that will generate strongly-typed proxy code for you.
Additionally you can use the standard HTTP verbs to access more POX (Plain old XML) or REST-based endpoints. Understanding how to consume these various service types is probably the best time spent a developer can educate themselves on understanding what will be right for their scenario. Here’s some resources:
The third point there, .NET RIA Services, is a new framework that aims to make accessing data simpler and more familiar. The link to the video will walk you through an introduction of that topic. RIA Services is best when you own the database and are hosting services in the same web application that will be serving up the Silverlight application.
Asynchronous access
All data access in Silverlight is asynchronous. This is perhaps another area that gets typical web developers tripped up initially. For example in the server world it would be reasonable to see something like this:
MyWebService svc = new MyWebService();
string foo = svc.GetSomeValue();
MyTextBox.Text = foo;
In Silverlight you wouldn’t be able to do that synchronous call. To those who haven’t done asynchronous programming before this can be confusing, but it is well worth the learn. Using the above pseudo code, in Silverlight you’d do something like this:
MyWebService svc = new MyWebService();
svc.Completed += new CompletedHandler(OnCompleted);
svc.GetSomeValue();
void OnCompleted(object sender, EventArgs args)
{
MyTextBox.Text = args.Result;
}
Notice that you use the result of the service call in a completed event handler. This is the pattern that you will see over and over again with basic service access.
Cross Domain Data Access
Since Silverlight is a web client technology, it operates in the browser’s secure sandbox area and are limited to certain access policies. One of these restrictions is referred to as cross-domain access. That is that your application hosted in one domain cannot access services in another domain unless the service says you can. This “opt-in” approach is commonly known as cross-domain policy files. Silverlight, like other rich client plug-ins, conforms to these policies. This is an area that you as a Silverlight developer will likely hit at some point. Educate yourself sooner than later. Here are some pointers:
COMMON MYTH: You need the Silverlight and the Adobe cross-domain policy files in your service to enable access. This is NOT TRUE and I see it to often people saying I have crossdomain.xml and clientaccesspolicy.xml and it still doesn’t work. If you are building a service for Silverlight consumption via cross-domain, you only need the clientaccesspolicy.xml file format – that is what we look for first and is the most flexible and secure for Silverlight.
Using Style Elements to improve the look and feel of your UI
Silverlight support a Style mechanism that allows us to encapsulate control property values as a reusable resource. We can store these style declarations in separate files from our pages, and re-use them across multiple controls and pages in an application (as well as re-use them across multiple applications). This is conceptually similar to using CSS with HTML when doing basic customization scenarios.
Note: In addition to defining basic property settings (Color, Font, Size, Margins, etc), styles Silverlight can also be used to define and re-use Control Templates - which enable super rich skinning and adaptation of control structure (and support customization scenarios not possible with CSS in HTML today).
Let's start by encapsulating styles for the <Border> control (and the <TextBlock> title contained within it) of our sample page:
We can create two Style elements within our App.xaml file that encapsulate the <Border> and <TextBlock> settings we were previously declaring inline using the markup below:
Note how we are giving each Style a unique "Key" value above. We can then update our <Border> and <TextBlock> controls to reference the Styles using these keys. We'll be using a XAML feature called "markup extensions" to do this. Markup extensions are used when there are non-literal values that we want to set (another example of where we'll use this feature is with databinding expressions).
When we update the other controls within our Page.xaml file to use styles as well, we are left with a file that looks like below:
Encapsulating the style settings this way allows developers to better focus on the behavior semantics of the application, and also enables us to re-use styles across other controls/pages we build.
Making controls look really spiffy (using Control Templates on individual controls)
One of the most powerful features of the WPF and Silverlight programming model is the ability to completely customize the look and feel of the controls used within it. This allows developers and designers to sculpt the UI of controls in both subtle and dramatic ways, and enables a tremendous amount of flexibility to create exactly the user experience desired.
In this tutorial segment we'll look at a few ways you can customize controls, and then close out by polishing up the user interface of our Digg application using these techniques.
Customizing what goes inside a control (its content)
if we create a simple button with text saying “Push Me”, it will be displayed something like this:
We could use Shape controls (like the Ellipse control below) to create custom vector graphics inside the button.
Customizing Controls using Control Templates
The control model used by Silverlight and WPF allows you to go much further than just customizing the inner content of a control. It optionally allows you to completely replace a control's visual tree with anything you want - while still keeping the control behavior intact.
For example, let's say we don't want our buttons to have the default rectangle push button look, and instead we want them to have a custom round button look like below:
We could accomplish this by creating a "RoundButton" style in our App.xaml file. Within it we'll override the Button's "Template" property, and provide a ControlTemplate that replaces the Button's default Rectangle visual with an Ellipse control and a TextBlock inside it:
We can then have a <Button> control reference this Style resource to use this "RoundButton" look and feel:
In Summary
Silverlight remains one of the most exciting client side technologies to emerge on today’s web development landscape. A large part of its power comes from the underlying, proven .NET framework – but a large part of it is written from the ground up.
To accomplish some of the things that the Silverlight runtime does (with just a few lines of code) – such as fast playback speeds (allowing multiple videos to play simultaneously), platform neutral WMV playback, smooth full-screen transitions etc. - takes days and weeks to program on other leading web platforms.
Silverlight provides not just a more efficient – but a more visually appealing alternative to tasks that are part of today’s Rich Interactive Applications.
This articles has provided an in-depth introduction to Silverlight, its features, its shortcomings as well as a step-by-step guide for building various ‘Hello Worlds’ illustrating the many facets of Silverlight programming.