DevX HomePage

Extending Silverlight to WPF (and Vice-Versa)

Although most Windows® Presentation Format (WPF) and Microsoft® Silverlight™ applications are designed to cover widely differing scenarios, there are cases where it is desirable to use both technologies to create complimentary programs. In such cases it is, of course, advantageous to coordinate the construction of both applications in order to achieve both efficient development and long term maintainability.

Scenarios More Suitable to Either WPF or Silverlight

WPF is designed to provide Windows desktop applications with access to rich user interface features such as animation, 3D graphics, audio and video, as well as direct access to graphics acceleration hardware in order to achieve much better graphics performance. Most WPF applications, since they run locally on the user's computer, do not involve the same security restrictions as web applications. WPF applications can, therefore, store their data on the user's computer with few, if any, restrictions on access to the file system. Also, since the application does not have to be downloaded from some remote location, there is little reason for the applicable Microsoft .NET® Framework not to include the full panoply of features which have been created.

Silverlight, on the other hand, is designed to provide a much broader reach than WPF by supporting multiple platforms—that now include not only Windows, but also Mac and, via an arrangement with Novel, Linux as well (Moonlight—currently matching Silverlight 1.0 although a Silverlight 2 equivalent is under development).

However, to achieve this broader scope, Silverlight must be capable of running in a number of different web browsers on these different platforms. This requirement imposes some structural limitations on Silverlight. For example, it is not possible to make certain assumptions regarding the availability of hardware and the APIs which can be used to access that hardware (e.g. Direct X® and the Windows Display Driver Model, neither of which are present on Mac or Linux).

Next, on the assumption that a very small size is critical to being a successful browser plug-in, Microsoft was required to omit many things which were present in the full .NET Framework, that otherwise would have been considered desirable if download file size were not such an important consideration. While it is probably true that as download speeds continue to increase, this restriction will be relaxed a bit over time, for the moment, as well as for the near to medium term future, this factor will continue to impede the ability of Silverlight to offer all of the features present in WPF.

Deciding which technology is more suitable to a given project is a subject unto itself. But at a high level, if access to graphics acceleration or those extra features only present in WPF is important, or if performance is paramount, WPF is the preferable platform. On the other hand, if you can live without the extra performance and features found in WPF and prefer additional reach to the Mac and Linux platforms, Silverlight should be your choice.

Scenarios Possibly Suitable to Both WPF and Silverlight

An application originally developed in WPF for use on Windows clients may at some stage become a candidate for extension to the Mac and/or Linux platforms. For example, when WPF was introduced (and long before Silverlight 2 existed), I built an XBAP application (XAML Browser Application), loosely based on a webcast by Filipe Fortes. This XBAP application included photos from and a description of a visit which I had made to Senegal in 2006. Unfortunately, however, my friend who accompanied me on that trip was never able to see this application because it simply wasn't practical for him to install the full .NET Framework on an Internet cafe computer in Zambia. By converting this application to Silverlight, I could easily make this content available to my friend—and frankly to many others who for varying reasons are unable or unwilling to install a copy of the full .NET Framework.

One interesting example of a case where an application was initially created for Silverlight but later converted to WPF is referred to in a Mike Tucker blog article. Tucker was looking for a profiler to assist him in tuning the performance of his Silverlight application. Not finding such a tool for Silverlight, he decided to create a WPF equivalent in order to use the profiling tools available for that technology.

Caliburn, an application framework designed to assist developers to implement various patterns such as MVC, MVP, Presentation Model (MVVM), Commands and Application Controller, is an example of an application simultaneously developed for both WPF and Silverlight. Similarly, developers of custom controls would almost certainly want to build versions of their controls for use with both technologies.




WPF and Silverlight Feature Comparison

While Silverlight is largely a subset of WPF, there are a few features in Silverlight which are not (yet) present in WPF. Moreover, there are also a number of features present in both technologies that are implemented in somewhat different fashions. Christopher Vigna of Vertigo Software has graciously permitted me to use the following diagram which visually illustrates this point.

Figure 1. WPF & Silverlight Compatibility Diagram (as of Feb. 2009). The set of features, which includes Dependency Properties, Style and Visual Tree are present in both technologies but with differing implementations.

There is no shortage of blog articles or forum comments on WPF and Silverlight differences. However, since both Silverlight and WPF are in a state of continuous development, it would be highly unreliable to examine various lists of differences in features from a collection of blog articles since there is a great likelihood that many, if not all, of these articles will be out of date at the time that you read them. The most authoritative source for a list of these differences would be the online MSDN® help files. While this too could be out of date, it nevertheless stands a good chance of being the most comprehensive, accurate and current source of information on this topic.

Nonetheless, it's still useful to examine the current differences between Silverlight and WPF, not only to show how to handle the two of them programmatically, but also to show where the capabilities of the two might merge in the future.

Data Binding
Data Binding is one of the most impressive features of WPF. Silverlight 2 supports a subset of the Data Binding structure with some important exceptions. For example, Silverlight does not support binding one UI element to another UI element as in the canonical WPF example of a Slider bound to a TextBox or TextBlock. Instead, Silverlight is limited to binding UI elements to standard .NET objects such as a numeric variable (e.g. binding a TextBlock to the time of day). Silverlight also does not support binding directly to XML data as can be done in WPF via an XmlDataProvider.

This does not mean that it is impossible in Silverlight to link the value of some property on one UI element to the value of some other property on a different UI element, but only that it cannot be done via Data Binding. To achieve this linkage in Silverlight requires a developer to write his own event handlers. While not as convenient as Data Binding, WPF also supports the event handler approach.

For an excellent detailed explanation of Silverlight Data Binding, I recommend this tutorial by Jesse Liberty and Tim Heuer.

It is also important to appreciate that even when both Silverlight and WPF contain the same class, that does not mean that both classes share all the same members. For example, the following screenshots illustrate how there are many more properties in the WPF version of the Binding class than in the equivalent Silverlight class. The principal explanation for these differences is the desire to maintain the smallest possible file size for the Silverlight browser plug-in. The absence of certain of these properties in the Silverlight version, for example the ElementName property, explains why it is not possible to bind UI elements to other UI elements in Silverlight when that capability is present in WPF.

Figure 2. List of Properties for the WPF Binding Class.

Figure 3. List of Properties for the Silverlight Binding Class.
Triggers

Triggers in WPF have proved to be very useful for starting and stopping Animations. Unfortunately, however, triggers are largely absent from Silverlight. Silverlight only supports EventTriggers and then only for the Loaded event and the BeginStoryboard action. Since one of the primary features of both WPF and Silverlight is the support for Animations, the absence of Triggers in Silverlight can have a significant impact on those applications which rely heavily on Animations.

To some extent, the absence of Triggers in Silverlight can be mitigated through the use of the VisualStateManager. Microsoft does plan to port the VisualStateManager to WPF. Once that happens, joint Silverlight/WPF development or application conversion will become easier.

Control Support
At present, WPF includes far more controls than Silverlight. Notable omissions from Silverlight include the FlowDocument, ToolBar, ListView, Menu, Context Menu and Ribbon controls. The MSDN Help Files include a comprehensive list detailing which controls are supported in WPF or Silverlight or both.

Control development for Silverlight is proceeding apace, however, as can be seen at the CodePlex site for the Silverlight Toolkit. This website reflects Microsoft's new development strategy regarding Silverlight controls which are now open source and available to developers from early beta stages. At present, there are approximately a dozen new controls for Silverlight in development working their way toward final release. For a comprehensive description of the Silverlight Toolkit, see my earlier article on this topic.

3D Graphics
3D graphics are not yet all that commonplace in WPF but at least support for it is available. Silverlight, by comparison, does not yet support 3D graphics.




Advance Planning Your Application

The absolute first step in advance planning your application is to conclusively determine whether or not you do, in fact, need both a Silverlight and a WPF version of your solutions. If one or the other type of solution can satisfy your needs, you can save a considerable amount of work by building only one solution instead of two. Moreover, by using only one technology you can take advantage of those features in that technology which are incompatible, either in whole or in part, with the alternate technology.

Assuming you do need both, next you'll need to identify where the structural differences between WPF and Silverlight may impact your particular project. This is especially true if neither the WPF nor Silverlight solutions have yet been significantly completed since advance planning may reduce the effort required to achieve multiple working solutions. For example, consider items which can be implemented in more than one way, one or more of which is not available in the other type of technology but one or more of which will work in both technologies. A good illustration of this point is inline content which in WPF can be implemented in the following fashion: <Button> my content </Button> While this implementation will not work in Silverlight, an alternative implementation which specifies content as an attribute will work in both technologies: <Button Content="my content" />. Similarly, while both WPF and Silverlight permit the application of a Style to a particular element by referencing the Style via its Key, only WPF allows for implicit styles to be applied using the TargetType attribute.

The next key decision which is required will be whether to start with a Silverlight project or with a WPF project. My recommendation is that with only rare exceptions it will be preferable to start with a Silverlight project. Since Silverlight is a subset of WPF, those application features which you are able to implement in Silverlight you'll almost undoubtedly be able to be implement in an identical or similar fashion in WPF.

Joint Development Guidelines

One obvious method for improving long term maintainability for two different versions of an application is to share files between the two projects. This can be achieved by creating the file in one project and then adding it as a link in the other project, rather than adding a copy as is the normal practice when adding an existing item.

Figure 4. This screenshot shows how to add a file as a link instead of as a copy.

Sharing a file in two different projects is not without its problems, however, since as has been discussed above, there are differences between what code will work in Silverlight and in WPF. In some cases, this can be resolved by using conditional compilation.

#if SILVERLIGHT
//Silverlight compatible code goes here
#else
//WPF compatible code goes here
#endif

While conditional compilation is only applicable to code behind and not to XAML, fortunately the area of XAML tends to have fewer incompatibilities between the two technologies.

In February (2009), Microsoft's Patterns and Practices group released Prism v2, a Composite Application Guidance for WPF and Silverlight. Prism v2 consists of a reusable code library, a reference (sample) implementation and documentation including various QuickStarts and Hands-On Labs. The collective purpose of these items is to assist developers in creating modular applications in either or both WPF and Silverlight. In this context the term modular application is intended to refer to an application consisting of a number of discrete, loosely coupled, independently evolvable pieces which interact with each other within the overall application. The premise here is that these modules can be individually developed, tested and deployed by different individuals or sub-teams and that these modules can later be modified or extended with new functionality more easily than a "monolithic" application.

While the initial version of Prism targeted only WPF, Version 2 is intended to apply to both WPF and Silverlight. The Prism V2 code libraries have been designed to permit the maximum degree of code sharing between WPF and Silverlight. Moreover, the reference implementation and the associated documentation are intended to provide explicit guidance and sample code focused on jointly developed WPF / Silverlight applications.

Post Development Conversion Guidelines

In the event that you are facing a situation where a project based on one technology is either complete or at least mostly complete and you have been asked to create a solution based on the alternate technology, a decision must be made as to whether to try to make a copy of the existing solution and mark it up or, alternatively, to start with a brand new solution and copy and paste in code from the existing solution as necessary. One advantage of using a fresh solution is that the applicable template from which the project type is created uses all the correct project settings whereas modifying an existing solution forces you to manually make (but hopefully understand), the changes required by these differences. If this is a "one off" conversion, it will likely be easier to begin with a new solution but if you expect to do this on multiple occasions, there is likely an advantage to forcing yourself to learn about the differences at the outset.

Summary

Anyone hoping for a painless, flip a switch, conversion between WPF and Silverlight is certain to be disappointed. Any conversion, regardless of the direction, or joint development will require considerable advance planning and implementation effort. However, if you follow the proper strategy and procedures, the process is quite feasible.

My recommended checklist consists of the following steps:

Links

  • Microsoft Silverlight, WPF and the Microsoft .NET Framework: Sharing Skills and Code (PDC 2008 Video by Ian Ellison-Taylor, General Manager for Microsoft's Presentation Platforms and Tools Team)


  • Silverlight-WPF Compatibility (MSDN Help File)


  • Silverlight Data Binding (Tutorial by Jesse Liberty and Tim Heuer)


  • Porting the Silverlight Dive Log Application to WPF (Blog article by Jonas Folleso)


  • Single Sourcing WPF and Silverlight (Blog article by Stefan Olson)


  • Silverlight Problems That Affect Me (Blog article about WPF / Silverlight Differences by Rob Eisenberg—dated)


  • Porting Silverlight 2.0 to WPF (Blog article by Mike Tucker—dated)


  • * 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).