DevX HomePage

An Introduction to the Silverlight Toolkit

Some developers have decried the lack of controls for Microsoft® Silverlight™. Now with the Silverlight Toolkit, developers have a plethora of controls to choose from for their applications.

The Silverlight Toolkit is Microsoft's effort to advance the control set for Silverlight developers. In its initial release the Silverlight Toolkit includes 12 controls. Even though the Microsoft-supplied controls for Silverlight now includes most, if not all, of the basic controls needed for typical Silverlight development, Scott Guthrie, Corporate Vice-President in for Microsoft's .NET Developer Division, has indicated that ultimately Microsoft expects to ship another 60+ controls for Silverlight.

The Silverlight Toolkit was posted on CodePlex on October 28, 2008. As we discuss below, this new delivery model represents a significant change in the way that Microsoft creates software for developers.

Categories of Controls
The controls included in the Silverlight Toolkit are organized into four separate categories:

By default, the Toolkit source code and samples use the XAML namespace prefix of "controls" for controls in the Common category. Those in the Input category use a namespace prefix of "input". Controls in the DataVisualization assembly use the prefix "charting".

Figure 1. This screenshot shows the XAML namespace conventions suggested by Microsoft for controls present in the Silverlight Toolkit.

Silverlight Controls Delivery Model
Microsoft has established four "Quality Bands" which represent the development state of the tools present in the Silverlight Toolkit. These bands consist of:

You can get the latest on the status of the controls and quality bands at the Silverlight Toolkit homepage on CodePlex.

Microsoft has announced that it plans a series of iterative releases which are targeted for 6 - 8 week cycles. Each new release will be posted on CodePlex. Individual controls after feedback and improvement are expected to make their way through the quality bands, eventually arriving at the Mature level. At that point, these controls may be added to the collection which is issued with the Silverlight 2 SDK or Silverlight Tools for Visual Studio® 2008. Some may also eventually make it into the Core Runtime. This follows the pattern set by the Beta 2 release of Silverlight which moved a number of frequently used controls into the Core Runtime in order to minimize the size of application downloads.

As part of Microsoft's movement toward more open development, the Silverlight Toolkit includes full source code for all of its controls, unit tests and samples. All source code is available under the Microsoft Public License.

This new development structure presents advantages both to Microsoft and to Silverlight developers. Microsoft anticipates that this structure will result in earlier and more extensive feedback from developers who test and use these controls prior to their achieving Mature status. Developers, on the other hand, because of the availability of source code and unit tests for these controls are in a position to better understand their workings and APIs. This will enable them to both report bugs and in many instances to suggest fixes for bugs. Developers are also better positioned to suggest or add features to these controls which can then make their way into the released version of the controls. It is also hoped that the involvement and contributions of developers to this process will result in a reduction of the time required for the development process of these controls.

To illustrate the content of the Silverlight Toolkit, we have selected what we consider to be three of the most interesting controls for closer examination (TreeView, Charting and the AutoCompleteBox). Later we will also look at Theming.

TreeView Control
Of all the controls in the Silverlight Toolkit, Microsoft's Shawn Burke says the one that received the most developer requests was the TreeView. The Silverlight TreeView is quite similar to its Windows® Presentation Format (WPF) equivalent, including support for data binding and the HierarchicalDataTemplate class. One of the features that WPF's TreeView supports, but Silverlight's currently does not, is UI virtualization. However, you can get some of the benefits of virtualization by handling the TreeViewItem's Expanded and Collapsed events.

Figure 2. Sample screenshot of a restyled Silverlight TreeView (names from the Northwind database, photos from Microsoft Office Online Clip Art).

The basic idea behind virtualization is to create only just enough visual elements to display the data that the user is currently viewing. A large hierarchical data collection could contain tens of thousands of items. If your code tried to immediately create visual elements for all of them at once, performance may suffer. But initially you only really need to create just a screenful of visual elements for the highest level of the TreeView. As the user drills down into the TreeView by expanding its nodes, your code can handle those Expanded events. In that event handler you would create just enough new visual elements to display the top level of the newly revealed branch. For sample code to implement this, see this thorough tutorial by Justin Angel.




Charting
Charting is an area where the Silverlight Toolkit really excels. The collection of charts which it offers and the flexibility with which they can be manipulated are very impressive.

If you don't have a background in charting it would be useful to review one or two tutorials on charting to familiarize yourself with the basics of chart building. There are a number of good online tutorials available for Microsoft Office® Excel charts, particularly one by Jon Peltier. Of course, the same set of general principles for using charts to display information applies regardless of the application used to create the charts.

There are two other very important resources for learning about the Silverlight Toolkit charting controls: the charting sample application included in the Silverlight Toolkit and the ChartBuilder application available from David Anson, a member of the Silverlight Toolkit development team with responsibility for charts. Both of these resources are discussed in the section entitled Silverlight Toolkit Help File and Sample Collections, below.

Our experience is that the terminology of charts is not particularly intuitive. In particular, the three key terms here; Series, DependentValue and IndependentValue do not have obvious meanings. Therefore, let's look at an example to understand the meaning of these terms. For this purpose we will use a column chart which will plot the median value of existing home sales by regions over the past four years. The source of data for this chart comes from the National Association of Realtors. This data indicates that housing prices peaked in 2006 and have declined each year since then. Median home prices are highest in the Western region and lowest in the Midwest.

When put into Excel, our data looks like this:

Figure 3. Chart data entered in Excel.

Column A lists the years from 2005 to 2008. Since our goal is to display median home prices in each of those years, the values from A2 - A5 represent the IndependentValues and the values in cells B2 - F5 represent the DependentValues. Usually this distinction should not be hard to spot. DependentValues represent the values that we will plot in the body of the chart while IndependentValues will make up the labels which correspond to the DependentValues. It's not accurate to say that IndependentValues are always shown at the bottom of the chart, for while that is true in the case of a column chart, it is not true for other types of charts such as bar charts or pie charts. Nor can you assume that IndependentValues always will come from a column in your spreadsheet. In this example we could just as well have used B1 - F1 as our IndependentValues. In that case B2 - F5 would still constitute our DependentValues but A2- A5 would be the Series, as explained in the next paragraph.

When your Excel spreadsheet contains only one column of DependentValues, there will be only a single Series. Where, as in this case, there are five columns, there are five Series. In effect Series represent the titles for each of your columns of DependentValues. In a chart, Series are displayed in the Legend. Normally your Series can also be described in the aggregate—which in a chart is represented by the LegendTitle ("Region" in the current example).

By definition, the code for every chart will always require a Silverlight Chart element. The chart title and the legend title are both properties of the Chart element. Moreover, since there will always be at least one set of DependentValues, there must always be at least one Series. In Silverlight, Series is a direct child of the Chart element, as shown in the following screenshot.

Figure 4. This code illustrates most of the key elements of a Silverlight chart.

The ItemsSource property of each ColumnSeries element is bound to an ObservableCollection of custom MedianHomePriceRecord objects, each of which has a Year property (the IndependentValue in our case) and a Price property (the DependentValue in our case) which correspond to the values shown in Figure 3. In this case, the assignment of the ObservableCollection to the ItemsSource property takes place in the Page_Loaded event handler (not shown. but for complete source code see www.WPFLearningExperience.com).

The resulting chart is shown in the following screenshot:

Figure 5. Screenshot of finished chart.

This chart can be converted into a bar chart merely by substituting BarSeries for every reference to ColumnSeries in our code.

Figure 6. Screenshot of our chart converted into a bar chart.

While it is equally easy to convert this chart into a pie chart, the resulting effect is rather overcrowded, thus illustrating that not every chart is suitable for every set of data.

Figure 7. Sample Silverlight Line Charts.

Silverlight Charting also includes many different line, scatter and animation type charts which can also be previewed simply by making this same Series replacement. As mentioned previously, not every type of chart makes sense for every set of data but previewing them is very easy.




AutoCompleteBox
The AutoCompleteBox is another interesting control that can add some very appealing style points to your application. The prototypical example of where to use an AutoCompleteBox is a textbox which represents either the departure or destination airport on an airline website. Naturally the airline doesn't want to permit users to select an airport to which it doesn't fly, so it compiles a list of valid airports from its route map. For a regional airline this list may be short enough to be contained in a ComboBox but for one of the majors (or for a consolidator such as Travelocity or Expedia), the excessive number of entries in a ComboBox can result in a highly sub-optimal user experience. This is where the AutoCompleteBox can come to the rescue.

An AutoCompleteBox generally looks like a textbox but it can be styled to look like a ComboBox.

Figure 8. An AutoCompleteBox styled to look like a ComboBox.

The AutoCompleteBox has an ItemsSource property which can be set to the collection of valid values from which the user is permitted to choose. The AutoCompleteBox can even use a Web Service call to generate a context sensitive list of alternatives to present to the user. One example illustrated in the Silverlight Toolkit Sample Collection (discussed below) involves a Web Service call to Microsoft Live Search.

In either case, once the user begins to type, a list of acceptable options appears in a drop down list. This list can be styled in any fashion that you prefer. Using multiple elements in the drop down list, as shown in the following screenshot, can be accommodated by setting the ItemTemplate property with a DataTemplate containing multiple XAML elements.

Figure 9. This screenshot shows an example of an AutoCompleteBox styled drop down list.

Not only can the AutoCompleteBox facilitate user selection from a fixed list of valid responses but it can also reduce the user's required typing if the IsTextCompletionEnabled property is set to True (the default). This option affords the familiar down arrow and tab completion procedure.

The AutoCompleteBox supports three different SearchMode options: Contains, StartsWith (the default) and StartsWithCaseSensitive. If the SearchMode property is set to Contains, matching text in the drop down list of acceptable alternatives can be styled to highlight the user entered text.

Theming
The Silverlight Toolkit introduces support for theming. There are six themes included with the first release and since the theming structure is extensible, third parties can add other themes as well.

Figure 10. Screenshot of a theming sample application.

Each theme is essentially a large XAML file containing custom modifications of the default styles and templates for many of the Silverlight controls: Button, Slider, etc. Although the raw XAML for the individual themes is available in a collection of resource dictionaries, developers normally would simply use the pre-built assemblies containing a specific theme.

You can apply a theme to anything from a single control up to your entire application element tree. Since the theme classes are ContentControls, you apply them by making the target element(s) the content of a theme instance.

The theming system is implemented using the new ImplicitStyleManager (ISM) static class. ISM mimics the implicit styling behavior built into WPF, but not yet directly implemented in Silverlight. Essentially ISM walks an element's tree of logical descendents applying a given set of styles. Since the style of a Silverlight element can only be set once in an element's lifetime, if you want to change themes dynamically at runtime, you need to recreate a fresh copy of the element tree or subtree to which the theme is applied.

Another characteristic of ISM is that it will not apply a style inside any nested UserControls that it encounters. This is demonstrated in the theming screenshot, above, where in each case the nested UserControl retains its blue border and gold background. This is because the nested UserControl lives in its own separate namescope outside the logical tree to which ISM is applying styles. Although the UserControl is in the parent's visual tree, it is not in its logical tree. If desired, one way to apply theming to a nested UserControl would be to set an additional theming container around the nested UserControl.

The Silverlight Toolkit Help File and Sample Collections
The Silverlight Toolkit download package includes a standalone help file (Silverlight Toolkit.chm). Since at any given time the Silverlight Toolkit will likely contain a significant percentage of controls which have not yet advanced to the Mature (i.e. released) state, help regarding all of these controls will not be available in the Visual Studio integrated help system. Accordingly, developers are advised to keep this standalone help file handy for convenient reference. It will also allow you to stay informed regarding new releases of the Silverlight Toolkit in order to ensure using only the most up to date help content (and of course the controls themselves).

As most experienced developers well know, one of the most efficient techniques for writing code is to mark up a good piece of sample code to tailor it to the specifics of the current task. For this reason, the authors of the Silverlight Toolkit have included a very large set of sample applications.

Figure 11. Screenshot of the Silverlight Toolkit Control Sample Collection.

This sample collection includes a lot of explanatory text in addition to extensive code examples. The sample collection is exposed both in the form of a compiled Silverlight application and as a multi-project Visual Studio solution. The compiled application is the most convenient format for learning about the various controls as the application is structured to explain each of the key elements for included controls. For additional details not described by the compiled application, one can refer to the underlying project. Overall, the sample collection represents an enormously useful structure for learning about and using the Silverlight Toolkit controls.

There is also a second collection of samples in the Silverlight Toolkit, this one devoted to charting samples.

Figure 12. Screenshot of the Silverlight Toolkit Charting Sample Collection.

The charting sample collection is organized in the same manner as the sample collection for the other Silverlight Toolkit controls.

There exists another important resource for Silverlight charting, namely the ChartBuilder application available from David Anson's Blog. This application affords a structure which allows you to experiment with different properties of the various Silverlight Toolkit charts. With live feedback, you can change a value and see exactly what impact this change has on your chart.

Figure 13. Screenshot of the ChartBuilder application illustrating how a change in any of the three textboxes on the left will be immediately reflected in the TextBlocks in the application. Of course, the same is true of the chart data as well.

Notice too how the textbox in the lower right corner of the ChartBuilder application (below the chart itself), contains the XAML which corresponds to the property value selections which you have made. Once you have designed the chart in the manner that you want, you can copy and paste the generated XAML into your own application.

Summary
The Silverlight Toolkit contains a large selection of new controls for developing Silverlight applications. Each of these controls includes full source code and an extensive set of sample applications illustrating their use.

None of the controls contained in the first release of the Silverlight Toolkit are yet in release to web (RTW) condition. A key goal of the Silverlight Toolkit is to make unfinished controls available to Silverlight developers at an early stage in order to solicit comments, suggestions and bug reports. The hope is that this will result in both a shorter development cycle and better quality controls.

While some of the controls in the Silverlight Toolkit are not particularly exciting (e.g. Label, NumericUpDown) others such as those highlighted in this article (TreeView, Charting and AutoCompleteBox) are actually very impressive. In addition, the Silverlight Toolkit includes theming support which can be very easily applied to all or any portion of Silverlight content.

Links

  • Silverlight Controls Roadmap (PDC Session Video—Shawn Burke, Product Unit Manager of the WPF/Silverlight Controls Team)


  • Silverlight Toolkit Now Available for Download (Release Announcement by Shawn Burke)


  • Silverlight Toolkit: TreeView, TreeViewItem & HierarchicalDataTemplate (Blog article by Justin Angel)


  • Collection of Silverlight Charting Resources (Compilation on David Anson's Blog)


  • Chartbuilder Application (Compliments of David Anson)


  • Styling the Charts in the Silverlight Toolkit (Pete Brown Blog Article)


  • Build a highlighting AutoCompleteBox (like IE8 and Firefox 3) in 5 minutes (Jeff Wilcox Blog Article)


  • Using Silverlight AutoCompleteBox on Custom Types (Tim Heuer Blog Article)


  • Use Styles for an Editable Silverlight ComboBox (Tim Heuer Blog Article)


  • Using ImplicitStyleManger and Theme Containers (Unfold Blog Article)
  • * This article was commissioned by and prepared for Microsoft Corporation. This document is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.


    Cal Schrotenboer is a C# developer with experience in building Windows Forms application front ends for SQL Server databases. He also teaches programming classes at Foothill College in Los Altos Hills, California and Microsoft Network Administration (MCSE) classes at Mission College in Santa Clara. Cal maintains a WPF blog at www.WPFLearningExperience.com. His outside interests include travel and photography (www.travelswithcal.com).
    Alan Cobb is an independent consultant specializing in .NET programming in C# for Silverlight and WPF. He has been a consultant for over 20 years in using Microsoft systems and languages, doing contract work for clients including Oracle and Microsoft. Alan has a Silverlight/WPF technical blog at www.alancobb.com/blog.