Microsoft Wpf Silverlight Comparison Whitepaper V1 1

5,812 views

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,812
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
178
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Microsoft Wpf Silverlight Comparison Whitepaper V1 1

  1. 1. Silverlight / WPF Comparison Whitepaper. Programmatic Differences Between Silverlight and WPF A Whitepaper by Wintellect, LLC Version 1.1 Build 0000 Information in this document is subject to change without notice. Any example companies, organizations, products, people, and events depicted herein are fictitious. No association with any real company, organization, product, person or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarked, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. © 2009 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, MS, Windows, Windows NT, MSDN, Active Directory, BizTalk, SQL Server, SharePoint, Outlook, PowerPoint, FrontPage, Silverlight, WPF, Visual Basic, Visual C++, Visual J++, Visual InterDev, Visual SourceSafe, Visual C#, Visual J#, and Visual Studio are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. Other product and company names herein may be the trademarks of their respective owners. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 1 of 70 www.wintellect.com
  2. 2. Silverlight / WPF Comparison Whitepaper. TABLE OF CONTENTS Table of Contents ...............................................................................................................................2 Introduction ......................................................................................................................................5 Similarities Between Silverlight and WPF ............................................................................................5 Dependency Properties .......................................................................................................................... 6 Controls .................................................................................................................................................. 6 Animations .............................................................................................................................................. 7 Custom Controls ..................................................................................................................................... 7 User Controls ...................................................................................................................................... 8 Video ....................................................................................................................................................... 8 Ink and Stylus .......................................................................................................................................... 9 Differences Between Silverlight and WPF ...........................................................................................9 Architecture ............................................................................................................................................ 9 Deployment .......................................................................................................................................... 10 BAML/XAML ...................................................................................................................................... 10 XAML..................................................................................................................................................... 11 XAML Language................................................................................................................................. 11 Triggers ............................................................................................................................................. 12 Visual State Manager ........................................................................................................................ 13 Markup Extensions ........................................................................................................................... 14 User Interface ....................................................................................................................................... 15 Keyboard ........................................................................................................................................... 16 Mouse ............................................................................................................................................... 17 IsEnabled........................................................................................................................................... 19 Local File Access ................................................................................................................................ 20 Sub-Pixel Rendering .......................................................................................................................... 20 Font Support ..................................................................................................................................... 21 Graphics ............................................................................................................................................ 22 Kiosks ................................................................................................................................................ 24 Object Trees ...................................................................................................................................... 25 Control Library ...................................................................................................................................... 27 General ................................................................................................................................................. 30 Routed Events ................................................................................................................................... 30 Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 2 of 70 www.wintellect.com
  3. 3. Silverlight / WPF Comparison Whitepaper. Data-Binding ..................................................................................................................................... 30 Networking ....................................................................................................................................... 35 Local Isolated Storage ....................................................................................................................... 37 Resource Dictionaries ....................................................................................................................... 39 Custom Dependency Properties ....................................................................................................... 40 Commanding ..................................................................................................................................... 41 .Net Framework .................................................................................................................................... 41 Collections ........................................................................................................................................ 41 Cryptography .................................................................................................................................... 42 Threading .......................................................................................................................................... 43 WPF Specific Functionality ............................................................................................................... 44 Desktop Functionality ........................................................................................................................... 44 Printing ............................................................................................................................................. 44 XPS Documents ................................................................................................................................. 44 Speech .............................................................................................................................................. 46 InterOp .............................................................................................................................................. 47 XAML..................................................................................................................................................... 48 Styles ................................................................................................................................................. 48 User Interface ....................................................................................................................................... 49 3D Graphics ....................................................................................................................................... 49 Themes ............................................................................................................................................. 49 Skins .................................................................................................................................................. 50 Image Manipulation .......................................................................................................................... 50 Page-Based Navigation ..................................................................................................................... 51 Input Gestures .................................................................................................................................. 52 General Functionality ............................................................................................................................ 53 Freezable Objects.............................................................................................................................. 53 Data Providers................................................................................................................................... 53 Validation .......................................................................................................................................... 54 Dynamic Resources ........................................................................................................................... 57 Code Access Security......................................................................................................................... 57 Silverlight Specific Functionality ....................................................................................................... 58 Web Functionality ................................................................................................................................. 58 Browser InterOp ............................................................................................................................... 58 Media .................................................................................................................................................... 60 Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 3 of 70 www.wintellect.com
  4. 4. Silverlight / WPF Comparison Whitepaper. Traditional Streaming........................................................................................................................ 60 Progressive Download ...................................................................................................................... 60 Smooth Streaming ............................................................................................................................ 60 Timeline Markers .............................................................................................................................. 61 Deep Zoom ........................................................................................................................................... 62 Code Reuse Strategies ...................................................................................................................... 63 User Controls ........................................................................................................................................ 63 Compiler Directives ............................................................................................................................... 63 Linked Files ........................................................................................................................................... 64 Coding Scenarios ................................................................................................................................... 65 Element-to-Element Binding ............................................................................................................. 65 Multi-Data Binding ............................................................................................................................ 67 Triggers / Visual State Manager ........................................................................................................ 68 Fonts ................................................................................................................................................. 69 Summary ......................................................................................................................................... 70 Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 4 of 70 www.wintellect.com
  5. 5. Silverlight / WPF Comparison Whitepaper. INTRODUCTION The Windows Presentation Foundation (WPF) is Microsoft’s latest development platform for building next-generation Windows client applications. Silverlight, a subset of WPF, extends the platform to the web via the add-on mechanism available in most current browsers. As a subset of WPF, the ability to create rich Internet applications is unprecedented; however, there are some significant differences between the capabilities of Silverlight and WPF, as well as important differences in the programming features of the two technologies. There are several architectural reasons for the discrepancies between WPF and Silverlight. First and foremost is that Silverlight 2 is a downloadable plug-in running within a browser. In order to insure that the plug-in is a small as possible, Microsoft built a smaller version of the .Net Framework, one that is highly optimized for size and is a small subset of the full .NET Framework, to embed within it. WPF, on the other hand, has full access to the main .Net Framework and all its associated assemblies. The difference between the smaller, downloadable .Net Framework and the full desktop version is one of the major disparities between the two platforms. In addition, the fact that Silverlight is rooted within the browser, and inherits the limitations of that environment, further differentiates the two platforms. This whitepaper documents both the identical (or nearly so) functionality as well as the differences. WPF and Silverlight have many technological concepts in common: Dependency Properties, Data Binding, Custom Controls and Animation to name a few. In addition, this paper documents functionality implementations that may be available in only one technology or the other. For example, WPF implements a large library of controls for document handling, including printing and formatting large documents. Finally, this whitepaper outlines some strategies in obtaining code reuse across both technologies. Due to minor differences in implementations of common elements, developers need to carefully plan their development in order to reuse code in both platforms. Of course, since certain functionality may not exist in one platform, developers may need to reduce the scope of the application in those cases. One last note about this whitepaper: where appropriate, some information about the future version of Silverlight 3 has been provided. Please note that Silverlight 3 is currently in beta and any information may be subject to change. In addition, more Silverlight 3 information can be found at www.silverlight.net. SIMILARITIES BETWEEN SILVERLIGHT AND WPF Silverlight is generally considered to be a subset of WPF. There are very few pieces of functionality that exist solely within the Silverlight platform. That stated, though the two platforms have their differences, much of the implementations are similar. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 5 of 70 www.wintellect.com
  6. 6. Silverlight / WPF Comparison Whitepaper. DEPENDENCY PROPERTIES Dependency properties are a key foundation for both Silverlight and WPF. Both platforms implement dependency properties in nearly identical ways; WPF allows for slightly more fine tuning the metadata when registering a dependency property. The template for defining a dependency property looks as follows: C# public string MyProperty { get { return (string)GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } } public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(MyClass), new PropertyMetadata("")); VISUAL BASIC Property MyProperty() As String Get Return CType(GetValue(MyPropertyProperty), String) End Get Set(ByVal value As String) SetValue(MyPropertyProperty, value) End Set End Property Public Shared ReadOnly MyPropertyProperty As DependencyProperty = _ DependencyProperty.Register("MyProperty", GetType(String), _ GetType(MyCustomClass), New PropertyMetadata("")) In essence, the backing store of a standard class’ property is an object of type DependencyProperty instead of what would normally be a private field. By convention, the backing store appends the word “Property” to the end of the actual class’ property name. The Register() static method accepts a class of type PropertyMetadata that, among other things, sets the default value of the property. The differences between Silverlight and WPF reside in the metadata structure: Silverlight only supports the PropertyMetadata class here, while WPF supports several classes (all derived from PropertyMetadata). CONTROLS Silverlight and WPF have a number of controls in common. Those controls not available in Silverlight can usually be found in either the Silverlight SDK or the Silverlight Toolkit. However, the implementation of the controls is not exactly the same in both platforms in most cases. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 6 of 70 www.wintellect.com
  7. 7. Silverlight / WPF Comparison Whitepaper. Microsoft is committed to bringing both platforms closer in terms of supported controls and functionality, and with each successive version the control libraries become more similar. ANIMATIONS Both Silverlight and WPF implement an animation mechanism. Animation is a complex topic, so this paper will just focus on some of the rudimentary aspects of it. At a basic level, animation is simply controlling a dependency property’s value through time. For instance, moving an element from left to right involves changing its Canvas.Left property through time. One way WPF and Silverlight implement this functionality is through linear interpolation, a method of smoothly transitioning a property from one value to another over time. Below is a snippet of XAML showing a simple animation declaration to move a button from left to right over the course of one second. <Storyboard x:Name="ButtonAnimation"> <DoubleAnimation Storyboard.TargetName="MyButton" Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:1" From="0" To="200" /> </Storyboard> There are many ways to initiate the animation: through triggers (for WPF), the VisualStateManager (for Silverlight), EventTriggers within styles, or through procedural code. The linear interpolation can be modified somewhat by adding AccelerationRatio and DecelerationRatio properties to the animation. These attributes essentially create three linear interpolations for the entire animation in order to modify the starting and stopping speeds. For example, a designer would use these attributes to have an object gradually pick up speed or stop suddenly. Unfortunately, Silverlight does not implement these two attributes, but the effect can be duplicated using keyframe animations with linear interpolation. For more complex animations, WPF and Silverlight support keyframe animations, a method of animation specifying a value at a specific point in time (a keyframe). The animation system then interpolates the transition from one keyframe to the next. The method of interpolation can be as simple as a basic linear method seen before, discrete (that is, no interpolation), or more complex spline interpolations. One aspect of animation present in WPF is path-based animations. Silverlight, unfortunately, does not have the facility to animate an object along a pre-defined path. CUSTOM CONTROLS Due to the styling and templating capabilities of WPF and Silverlight, the need for custom and user controls is less than in older technologies. However, there are scenarios when the Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 7 of 70 www.wintellect.com
  8. 8. Silverlight / WPF Comparison Whitepaper. development of such a control becomes necessary; such as when no existing control supports the required functionality needed. WPF and Silverlight define two types of user creatable controls: user controls and custom controls. User controls can be thought of as composite controls while custom controls are either derived from existing controls or are something completely new and derived from the Control base class itself. See http://msdn.microsoft.com/en-us/magazine/cc721611 for a great article on creating custom controls within Silverlight. User Controls User controls are useful when needing to reuse a complex group of elements in multiple places within an application or across applications. User controls typically derive from the UserControl element and can be declared in XAML as follows: <UserControl x:Class="MyProject.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml > <!-- Content --> </UserControl> VIDEO There are a few controls to play video resources in WPF and Silverlight. The MediaPlayer class is the major element in playing video from within an application. The MediaPlayer class wraps the functionality of Windows Media Player and therefore supports all the file formats that it does (such as .wmv, .avi, and .mpg). However, the MediaPlayer class is used from procedural code only and has no provision for XAML markup. Additionally, the MediaPlayer class is only available within WPF. To declaratively use video in WPF or Silverlight, the MediaElement class is a FrameworkElement. Within WPF, the MediaElement wraps the functionality of MediaPlayer, which in turn wraps the Windows Media Player. However, since the MediaPlayer class does not exist in Silverlight the MediaElement is completely separate from any local media player. The following snippet shows a method for embedding video into a XAML page: <MediaElement Width="640" Height="480" Source="MyVideo.wmv" /> Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 8 of 70 www.wintellect.com
  9. 9. Silverlight / WPF Comparison Whitepaper. Since the MediaElement is a Framework element, it supports many options to control its look- and-feel. In addition, within WPF only, a MediaElement can be contained within a VisualBrush and be used to “paint” any UIElement’s brush properties (i.e. background, 3D surfaces, etc.). INK AND STYLUS Digital ink refers to a method of input using a stylus on a touch-sensitive surface. Tablet PCs, pressure-sensitive tablets, touch screens, and other electronic devices have the capability to create digital ink. In addition, the mouse may also be used as a stylus device, though it is generally more difficult to use in that manner. WPF defines stylus-based input to distinguish between the traditional mouse and one of the touch-based input devices (where the input mechanism could be a digital pen or even a finger). A special panel called an InkCanvas is the main element used to accept free-form ink input. The InkCanvas is useful for adding annotations to images and documents. WPF supports ink-based gestures as well found in the System.Windows.Ink.ApplicationGesture enumeration. These gestures allow a user to control a system using only the stylus to perform commands such as Up, Down, Cut, Paste, etc. Finally, since WPF allows the capture of handwritten text there is a facility for handwriting recognition. The class used to analyze handwriting is InkAnalyzer ; however, it requires adding references to several assemblies found on Tablet PC systems: IAWinFX.dll, IACore.dll, and IALoader.dll. In a Silverlight application, it is possible to get handwriting recognition through a server-side component. DIFFERENCES BETWEEN SILVERLIGHT AND WPF Silverlight is a XAML-based technology that runs within the sandbox of browser plug-in. As such, it implements a subset of both the .Net Framework and WPF functionality. Microsoft made the decision to cut features to reduce the download footprint of the Silverlight plug-in. Future versions of Silverlight will attempt to reduce the differences between the two platforms, and still retain a small download footprint. Microsoft will accomplish this feat by only downloading libraries that the Silverlight application actually uses. ARCHITECTURE The basic architecture of WPF is analogous to traditional WinForms development, with the addition of the Media Integration Layer (MIL). The MIL is wrapped by two core assemblies, Presentation Framework and Presentation Core. WPF applications are run on a Windows client platform, and, with the exception of browser-hosted applications, are hosted by the system. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 9 of 70 www.wintellect.com
  10. 10. Silverlight / WPF Comparison Whitepaper. Since WPF applications are run on the client, they have access to the full .Net Framework programming stack, including the browser-hosted model. Silverlight applications, on the other hand, run within the plug-in model of the hosted web browser. The plug-in contains all the core code libraries that Silverlight needs to run. However, in an effort to minimize the download time for installing Silverlight, the entire .Net Framework is not loaded, instead, Microsoft created the Core CLR, a distinct subset of the .Net Framework runtime libraries. The differences between the two .Net Framework libraries constitute the major hurdles for developers when building applications to run in both architectures. Shared libraries are not capable of being shared between platforms since the core referenced assemblies are different. Library assemblies must be targeted for one platform only; and therefore cannot be shared. However, this whitepaper will discuss various alternate methods for sharing similar code between the two platforms. DEPLOYMENT Obviously, there are significant differences in deploying a Silverlight application compared with deploying a WPF application. Silverlight applications are hosted within a web server and a web page. To minimize client download size, Silverlight uses an XAP archive. A XAP archive is a zip-compressed archive of the Silverlight application, plus a manifest file describing the content. Visual Studio automatically generates the XAP archive when using the Silverlight project template. WPF applications can be deployed as a standalone application, ClickOnce application, or a XAML Browser application. BAML/XAML BAML is a binary form of the XAML in a WPF application. When compiled and deployed, the text-based XAML is reconstituted into binary form for quicker processing. Technically, the XAML is not compiled, just compacted into an efficient binary format, though one can argue the semantics. In order to retrieve the XAML of a page or control dynamically, it must be compiled as an Embedded Resource. This will store the actual XAML as an embedded resource within the assembly. It is then possible to retrieve the XAML in code via the resource manager. C# Stream s = this.GetType().Assembly.GetManifestResourceStream("MyProject.MyControl.xaml"); Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 10 of 70 www.wintellect.com
  11. 11. Silverlight / WPF Comparison Whitepaper. VISUAL BASIC Dim s As Stream = _ Me.GetType.Assembly.GetManifestResourceStream("MyProject.MyControl.xaml") XAML The eXtensible Application Markup Language is a dialect of XML that both WPF and Silverlight use to describe the user interface. Both platforms support a separate code-behind file to contain .Net programming code to manipulate the elements and controls declared within the XAML. The code-behind model is the same one first introduced with .Net at its inception to provide a separation between procedural code and presentation. XAML Language Most of the XAML language is similar between WPF and Silverlight. Differences begin appearing with the available UI elements available to each platform. <UserControl x:Class="Sample" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Grid Background="LightGray"> <!-- Additional content added here. --> </Grid> </UserControl> Silverlight does require that the root element contain a default “xmlns” namespace declaration, whereas WPF can assume an implicit value. Additional namespaces added to the root element must point to assemblies that are deployed with the application. WPF applications can point to assemblies within the GAC or deployed elsewhere. TargetType Some elements use a TargetType attribute to specify the type of element being referenced. For example, Styles use TargetType to specify the type of element being styled. WPF can specify the type using the {x:Type} markup extension, or by using the short-hand notation that relies on the default TypeConverter for TargetType: <Style x:Key="MyButtonStyle" TargetType="{x:Type Button}"> … </Style> Silverlight can only use this short-hand notation to specify the TargetType: <Style x:Key="MyButtonStyle" TargetType="Button"> Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 11 of 70 www.wintellect.com
  12. 12. Silverlight / WPF Comparison Whitepaper. … </Style> Triggers WPF supports a trigger mechanism to respond to certain end-user actions, such as moving the mouse over a UI element, or pressing a button. Triggers are usually defined as part of a style, as follows: <Style x:Key="Triggers" TargetType="{x:Type Button}"> <Style.Triggers> <Trigger Property="IsPressed" Value="true"> <Setter Property="Foreground" Value="Green"/> </Trigger> </Style.Triggers> </Style> WPF supports multiple types of triggers, such as MultiTrigger, EventTrigger and DataTrigger. MultiTrigger’s allow more than one condition to be specified before the style is applied. For example, <Style x:Key="Triggers" TargetType="{x:Type Button}"> <Style.Triggers> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsMouseOver" Value="true" /> <Condition Property="IsSelected" Value="true" /> </MultiTrigger.Conditions> <Setter Property="Foreground" Value="Purple"/> </MultiTrigger> </Style.Triggers> </Style> EventTriggers are triggers that respond to RoutedEvents, and only activate animations, they cannot properties on elements. <EventTrigger RoutedEvent="Button.MouseEnter"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Duration="0:0:0.5" Storyboard.TargetProperty="Opacity" To="0.5" /> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 12 of 70 www.wintellect.com
  13. 13. Silverlight / WPF Comparison Whitepaper. DataTriggers and MultiDataTriggers are triggers that respond to changes in the underlying data bound to an element. An example of a DataTrigger, <Style TargetType="{x:Type ListBoxItem}"> <Style.Triggers> <DataTrigger Binding="{Binding Path=Amount}" Value="0"> <Setter Property="Foreground" Value="Red"/> </DataTrigger> </Style.Triggers> </Style> Since DataTriggers use the Binding syntax, more robust conditions can be specified through the use of binding converters, allowing the application to reduce a range of values to a boolean value. Additionally, the MultiDataTrigger, its syntax mirrors the MultiTrigger element, can be used to further define conditions. Silverlight, however, does not implement the trigger mechanism, but instead introduces a concept called the Visual State Manager. Visual State Manager The Visual State Manager was introduced in Silverlight 2 to simplify control over visual states and transitions. WPF does not currently implement the Visual State Manager, however, the WPF Toolkit (http://wpf.codeplex.com), contains a preview of the VisualStateManager for WPF in the March 2009 release. Within a ControlTemplate, the Visual State Manager would be used to define any number of visual states and effects. <Canvas x:Name="MyCanvas"> <vsm:VisualStateManager.VisualStateGroups> <vsm:VisualStateGroup x:Name="CommonStates"> <vsm:VisualStateGroup.Transitions> <vsm:VisualTransition To="Normal" GeneratedDuration="0:0:0.2" /> <vsm:VisualTransition To="MouseOver" GeneratedDuration="0:0:0.5" /> </vsm:VisualStateGroup.Transitions> <vsm:VisualState x:Name="Normal" /> <vsm:VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimation Storyboard.TargetName="MyShape" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" To="Yellow" Duration="0" /> </Storyboard> </vsm:VisualState> </vsm:VisualStateGroup> </vsm:VisualStateManager.VisualStateGroups> <!-- Add Canvas visual elements --> Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 13 of 70 www.wintellect.com
  14. 14. Silverlight / WPF Comparison Whitepaper. Within the application code, the state can be changed by a simple call to the VisualStateManager. C# void MyControl_MouseOver(object sender, MouseEventArgs e) { VisualStateManager.GoToState(this, "MouseOver", true); } VISUAL BASIC Private Sub MyShape_MouseEnter(ByVal sender As System.Object, _ ByVal e As System.Windows.Input.MouseEventArgs) VisualStateManager.GoToState(Me, "MouseOver", True) End Sub Note, however, that the VisualStateManager does not completely replace or duplicate the functionality found in the Trigger mechanism. For example, there is no support for anything similar to MultiTrigger or DataTrigger. Markup Extensions XAML processors support extensions to the markup language in order to provide additional functionality not found within the default processing. For example, default processing accepts literal values for attributes, but in some scenarios, the attribute should reference a previously constructed object or access a static object. The syntax for a XAML markup extension in an attribute is: <ElementName Attribute="{MarkupExtension …}"> Markup extensions can also be used as a property element, and visually are indistinguishable from the default element syntax. Markup extensions in the x: namespace (the default mapping for XAML namespace) are XAML-defined markups and are not specific to WPF. WPF has full support for markup extensions. The most notable are:  StaticResource  DynamicResource  Binding  RelativeSource  TemplateBinding  x:Type  x:Static  x:Null  x:Array Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 14 of 70 www.wintellect.com
  15. 15. Silverlight / WPF Comparison Whitepaper. WPF also supports the creation of custom markup extensions. Custom markup extensions should be named with the Extension suffix and derive from the MarkupExtension base class. Silverlight implements limited support for markup extensions, using only x:Null, StaticResource, Binding, and TemplateBinding. Also, since Silverlight doesn’t implement a public MarkupExtension class, there is no support for custom markup extensions. The Binding markup extension is the only extension that Silverlight supports that has a corresponding class accessible via code. Silverlight also doesn’t support the alternative syntax of adding the “Extension” suffix like WPF does. So, {x:Null} is valid, but {x:NullExtension} is not. Markup extensions, in Silverlight, can not specify constructor parameters by name. Therefore {StaticResource myKey} is valid, but {StaticResource ResourceKey=myKey} is not. USER INTERFACE Most interaction between a user and the application occurs through the user interface as events. In WPF and Silverlight, most events are Routed Events (see ROUTED EVENTS for more information on the differences in Routed Events between Silverlight and WPF). Each event, regardless of type, defines a delegate for handling purposes. The definition typically only varies the event arguments passed to the handler. C# public delegate void RoutedEventHandler( Object sender, RoutedEventArgs e ) VISUAL BASIC Public Delegate Sub RoutedEventHandler ( _ sender As Object, _ e As RoutedEventArgs _ ) This definition, in essence, is the base definition for all other UI related events. All routed event arguments derive from the base RoutedEventArgs class. This document will also discuss more specific routed events (such as mouse or keyboard events) in detail, so knowing that there are differences in the base class as well is important. The table below shows the implementation of the RoutedEventArgs base class and the differences between WPF and Silverlight. ROUTEDEVENTARGS Property WPF Silverlight Device Yes No Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 15 of 70 www.wintellect.com
  16. 16. Silverlight / WPF Comparison Whitepaper. Handled Yes Yes InputSource Yes No OriginalSource Yes Yes RoutedEvent Yes No Source Yes No Timestamp Yes No The Handled property can be set in the event handlers to indicate to other listeners that the event has been successfully handled already. In essence, setting the Handled property to true would let other controls in the event hierarchy (either bubbled up, or tunneled down) know that the event has been successfully handled. That stated, the other controls could potentially ignore the fact and provide additional functionality. Keyboard Most UI elements support the KeyDown and KeyUp events. In both Silverlight and WPF, the handler’s signature is: C# public delegate void KeyEventHandler( Object sender, KeyEventArgs e ) VISUAL BASIC Public Delegate Sub KeyEventHandler ( _ sender As Object, _ e As KeyEventArgs _ ) However there are some significant differences in between the implementations of KeyEventArgs in the two technologies. Property WPF Silverlight ImeProcessedKey Yes No IsDown Yes No IsRepeat Yes No IsToggled Yes No IsUp Yes No Key Yes Yes KeyboardDevice Yes No KeyStates Yes No SystemKey Yes No PlatformKeyCode No Yes Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 16 of 70 www.wintellect.com
  17. 17. Silverlight / WPF Comparison Whitepaper. In addition, the Key enumeration contains different values between Silverlight’s version and WPF’s. For example, Silverlight contains Key.Alt to represent the Alt key, while WPF’s enumeration contains Key.LeftAlt and Key.RightAlt. WPF also exposed two additional event handlers, PreviewKeyDown and PreviewKeyUp, that Silverlight does not implement. Non-Windows Platforms Microsoft released Silverlight plugins for both Windows and Mac OS X operating systems. WPF, on the other hand, is only currently supported on the Windows platform. There is a drive by the open source community to port Silverlight to Linux. The project, Moonlight, only supports Silverlight 1.0, but the Silverlight 2.0 equivalent is under development. Moonlight is a sub-project under the Mono umbrella (an attempt to port the entire .Net Framework to Linux). Currently, there is no push for porting WPF itself to Linux through the Mono project. See http://www.mono-project.com for more information. Silverlight supports non-Windows key trapping through the use of the PlatformKeyCode value returned as part of the KeyEventArgs class. However, the common Apple key on Mac platforms is available through the ModifierKeys enumeration in Silverlight only. Mouse Both Silverlight and WPF support mouse events to various degrees. The following table documents the different mouse events supported by the two platforms. Mouse Event WPF Silverlight LostMouseCapture Yes Yes MouseDoubleClick Yes No MouseDown Yes Yes MouseEnter Yes Yes MouseLeave Yes Yes MouseLeftButtonDown Yes Yes MouseLeftButtonUp Yes Yes MouseMove Yes Yes MouseRightButtonDown Yes No MouseRightButtonUp Yes No MouseUp Yes No MouseWheel Yes No PreviewMouseDoubleClick Yes No PreviewMouseDown Yes No PreviewMouseLeftButtonDown Yes No PreviewMouseLeftButtonUp Yes No PreviewMouseMove Yes No PreviewMouseRightButtonDown Yes No PreviewMouseRightButtonUp Yes No Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 17 of 70 www.wintellect.com
  18. 18. Silverlight / WPF Comparison Whitepaper. PreviewMouseUp Yes No PreviewMouseWheel Yes No The mouse events use several delegates for mouse handling. For those events reacting to a mouse button the following delegate is used: C# public delegate void MouseButtonEventHandler( Object sender, MouseButtonEventArgs e ) VISUAL BASIC Public Delegate Sub MouseButtonEventHandler ( _ sender As Object, _ e As MouseButtonEventArgs _ ) For those events reacting to other mouse events, such as moving, the following delegate is used: C# public delegate void MouseEventHandler( Object sender, MouseEventArgs e ) VISUAL BASIC Public Delegate Sub MouseEventHandler ( _ sender As Object, _ e As MouseEventArgs _ ) The last event handler delegate is only used within WPF and handles mouse wheel events: C# public delegate void MouseWheelEventHandler( Object sender, MouseWheelEventArgs e ) VISUAL BASIC Public Delegate Sub MouseWheelEventHandler ( _ sender As Object, _ e As MouseWheelEventArgs _ Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 18 of 70 www.wintellect.com
  19. 19. Silverlight / WPF Comparison Whitepaper. ) However, as in the Keyboard event handler, the two Mouse EventArgs classes are implemented differently in Silverlight than in WPF. The MouseEventArgs implementation: Property / Method WPF Silverlight GetPosition(IInputElement) Yes Yes LeftButton Yes No MiddleButton Yes No MouseDevice Yes No RightButton Yes No StylusDevice Yes Yes XButton1 Yes No XButton2 Yes No The MouseButtonEventArgs class adds some additional properties to the MouseEventArgs class. The additional implementation details are: Property / Method WPF Silverlight ButtonState Yes No ChangedButton Yes No ClickCount Yes No There is no difference between MouseEventArgs and MouseButtonEventArgs within the current release of Silverlight 2. However, due to the separation of the two classes in Silverlight, the assumption that future support for the additional MouseButtonEventArgs properties is likely true. In order to obtain right mouse button and wheel support in Silverlight, developers need to interact with the browser through JavaScript and pass the mouse data back to Silverlight. Since Silverlight is, at its core, a browser plug-in, it is reliant on the plug-in models of the browser. Most browsers have special handling for the right mouse click and wheel events, and therefore pose a problem for the Silverlight plug-in. However, there are several implementations solving this issue available on the web through the use of browser inter-operation capabilities. IsEnabled WPF’s UIElement base class implements the IInputElement interface, in which the Boolean property IsEnabled is defined. By setting this property, a developer can control whether all the nested children are enabled or not. In Silverlight, however, this interface is not implemented by UIElement, and the bubbling functionality of IsEnabled is lost. Possible workarounds are either the brute force method of setting each nested control independently or binding the IsEnabled property to a global setting. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 19 of 70 www.wintellect.com
  20. 20. Silverlight / WPF Comparison Whitepaper. Local File Access WPF applications have a full range of capabilities in accessing local file resources depending upon the requirements of the application. Silverlight, on the other hand, has very limited access to local resources. Currently, Silverlight needs to acquire permission from the user via the OpenFileDialog to obtain Read access to a local file resource. Silverlight can only write data to isolated storage, but this is subject to change in later implementations of Silverlight. OpenFileDialog From a user-interface point of view, the OpenFileDialog in both WPF and Silverlight are virtually identical. Both implementations allow for multiple files to be selected. The major difference between the two implementations is the handling of the selected file. In WPF, the file can be returned to the application as a path and the application can open it as it needs to (for writing or reading). In Silverlight file is returned to the application as a FileInfo object. The name of the file is known, but none of the path information is available. In addition, the Silverlight application can only obtain a read-only stream to the file (direct access to the file system is forbidden). A minor difference between the two implementations is the setting of the dialog’s title. WPF allows the application to set a title to the dialog window, while Silverlight does not. SaveFileDialog The SaveFileDialog allows an application to let the user decide where to store data. WPF can store information to the user’s system without any user interaction as well. The current implementation of Silverlight does not contain a SaveFileDialog class. The only method to persist data through sessions would be to use local IsolatedStorage. Unfortunately, this method would prevent the user from accessing the data outside the Silverlight application. Silverlight 3 Note The future release of Silverlight 3 will include an implementation for storing data on the local file system with the user’s permission through the use the SaveFileDialog. Sub-Pixel Rendering WPF uses a technology called Pixel Snapping to reduce anti-aliasing effects on UI elements. Silverlight uses Layout Rounding to achieve a similar effect. To turn Pixel Snapping on in WPF (pixel snapping is off by default) set the SnapsToDevicePixels property to true. <Rectangle x:Name="MyShape" SnapsToDevicePixels="True" … /> Or in code: Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 20 of 70 www.wintellect.com
  21. 21. Silverlight / WPF Comparison Whitepaper. C# this.MyShape.SnapsToDevicePixels = true; VISUAL BASIC Me.MyShape.SnapsToDevicePixels = True In Silverlight, the UseLayoutRounding property is set to true by default. To turn on sub-pixel rendering, set this property to false. <Rectangle x:Name="MyShape" UseLayoutRounding="False" … /> Or in code: C# this.MyShape.UseLayoutRounding = false; VISUAL BASIC Me.MyShape.UseLayoutRounding = False Font Support As expected, WPF supports all the fonts installed in the Windows operating system. Silverlight, however, natively supports only a handful of fonts. Additional fonts must be embedded within a Silverlight application in order to use them, or dynamically downloaded as needed (see FONTS later in this paper for how to do this). Supported local fonts for text elements in Silverlight are: Arial Arial Black Comic Sans MS Courier New Georgia Lucinda Grande / Lucida Sans Unicode Times New Roman Trebuchet MS Verdana Silverlight contains a fallback font called “Portable User Interface.” This is the font used if none is specified. However, it is merely an alias to the Lucinda Grande / Lucida Sans font face on Windows platforms; it may be different on other operating systems. According to Microsoft Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 21 of 70 www.wintellect.com
  22. 22. Silverlight / WPF Comparison Whitepaper. documentation, Lucinda Grande and Lucinda Sans are aliases for the same font and usually named together for compatibility reasons. Finally, there are several East Asian fonts that can be used if available on the local computer as well as additional ones if the local computer is running Windows or the Mac OS. Adding additional fonts in Silverlight is a simple as creating adding the required fonts either as TrueType (ttf) files or compressed into a Zip archive as Content Items to the project. Setting the FontSource of a TextBlock control to the resource containing desired fonts will set the appropriate font. The font can then be used as follows, where “Custom Font” is the name of a font stored in the CustomFont.ttf file: <TextBlock FontFamily="customfont.ttf#Custom Font"> Written in my Custom Font. </TextBlock> And from a zip archive: <TextBlock FontFamily="customfont.zip#Custom Font"> Written in my Custom Font. </TextBlock> In WPF fonts can be added as Content Items to the application, and are separate from the applications binary assemblies. To insure that the fonts are available to the application upon deployment, the CopyToOutputDirectory element should be set to “PreserveNewest.” Additionally, fonts can be added to a WPF application as Resource Items. The following XAML example shows how to reference a font resource: <TextBlock FontFamily="./resources/#Custom Font"> Written in my Custom Font. </TextBlock> Graphics Both Silverlight and WPF support vector-based drawing elements as well as support for raster images in a variety of formats. Most graphical functions in WPF are accelerated by offloading the graphics workload to the GPU. Silverlight, however, cannot hand off this processing to the graphics card, and therefore most perform all calculations in software. Silverlight 3 Note Silverlight 3 will support some hardware acceleration through two new parameters on the Silverlight plug- in, EnableGPUAcceleration and EnableCacheVisualization. Additionally, an entire panel can be cached and rendered by the GPU through the use of the new CacheMode property. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 22 of 70 www.wintellect.com
  23. 23. Silverlight / WPF Comparison Whitepaper. 2D Graphics Bitmap Effects Bitmap effects are simple pixel processing operations performed on WPF content. Since the bitmap effect occurs replaces the Visual object’s built-in rendering, bitmap effects are rendered in software instead of accelerated through hardware. There are five built-in bitmap effects implemented within WPF. In addition to the default Bitmap Effects, WPF allows the creation of custom effects. However, creating custom effects entails writing an unmanaged COM library containing the effects and a managed-code wrapper for integration into WPF. Silverlight does not support bitmap effects. In some cases, such as adding drop shadows, there are ways to work around the limitation by using duplicate elements and offsetting them from one another. For the more visually complex effects, such as blurring, there are no easy methods for recreating the effect. Silverlight 3 Note The future release of Silverlight 3 will include a form of bitmap effects called pixel-shader effects. The pixel-shader mechanism will perform many of the same effects previously unavailable to Silverlight applications, including writing custom pixel-shaders. Important Note: BitmapEffects are actively being discouraged by Microsoft and are being deprecated. Instead, the recommended approach is to use Effects; however, only blur and drop shadow effects have been created. Effects, not coincidentally, are written with the same pixel-shading technology that will be available to Silverlight 3; so shaders written today will be usable with Silverlight 3. Brushes Everything drawn on a WPF or Silverlight surface is visible due to brushes. Brushes draw everything from lines to backgrounds to text. Brushes come in several types and allow for great flexibility in their implementation. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 23 of 70 www.wintellect.com
  24. 24. Silverlight / WPF Comparison Whitepaper. There are a variety of brushes available to both Silverlight and WPF. Brush WPF Silverlight SolidColorBrush Yes Yes LinearGradientBrush Yes Yes RadialGradientBrush Yes Yes ImageBrush Yes Yes DrawingBrush Yes No VisualBrush Yes No TileBrush Yes No VideoBrush No Yes The lack of a TileBrush in Silverlight prevents both the Video and Image brushes from also being tiled. Kiosks Kiosks are typically defined as stand-alone devices with a complete user interface. Users are not allowed to access anything other than the kiosk application. WPF Kiosk To create a WPF kiosk, the application should be set to fill the entire screen and prevent the user from minimizing or otherwise interacting with any other part of the system. To force the application’s main window into a maximized, borderless form, the following XAML can be used: <Window x:Class="TestWPF.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Kiosk" WindowStyle="None" WindowState="Maximized" Topmost="True"> <!-- Add Window Content --> </Window> Additionally, the developers could trap certain key-strokes to prevent users from circumventing the application and accessing other system resources. Silverlight Kiosk Kiosks in Silverlight act slightly differently, because Silverlight applications cannot set the full- screen mode during instantiation or in the page’s Loaded event handler. Instead, full –screen mode can only be entered upon response of a user-initiated event such as a key-press. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 24 of 70 www.wintellect.com
  25. 25. Silverlight / WPF Comparison Whitepaper. The following code will switch from full-screen to normal mode when the user presses the Escape key (assuming the handler is attached to the page’s KeyDown event): C# void Page_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) App.Current.Host.Content.IsFullScreen = !App.Current.Host.Content.IsFullScreen; } VISUAL BASIC Private Sub Page_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) If e.Key = Key.Escape Then App.Current.Host.Content.IsFullScreen = _ Not App.Current.Host.Content.IsFullScreen End If End Sub Note, full-screen mode for Silverlight only forces the Silverlight application into full screen; any surrounding HTML is lost in full-screen mode. In addition, Silverlight also limits keyboard entry to the following keys: ESCAPE, UP, DOWN, LEFT, RIGHT, PAGE UP, PAGE DOWN, HOME, END, SPACEBAR, TAB, and ENTER. This limitation is by design so that a malicious web site is prevented from mimicking the system’s operating system to trick the user. Object Trees Visual Base Class The Visual base class is the class that all WPF visually rendering elements eventually derive from. It supports functionality such as printing and encoding the visual to a bitmap image. The Visual base class itself derives from DependencyObject. Silverlight does not implement the Visual base class. Instead Silverlight UI elements have several different class hierarchy structures. Controls, such as TextBox and Button, derive from the Control base class, FrameworkElement, UIElement and then from DependencyObject. Other UI Elements, such as Panel or TextBlock, do not inherit from the Control base class, but still have FrameworkElement and UIElement in their base class hierarchy. Note that this list is not the absolute hierarchy for all controls, just some common base classes that developers can rely upon existing somewhere in the chain of base classes. Even though Silverlight and WPF UI elements ultimately derive from DependencyObject, the class has little to do with UI rendering. Instead the DependencyObject class allows objects to participate in the dependency property system. DependencyObject classes are not necessarily visual elements. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 25 of 70 www.wintellect.com
  26. 26. Silverlight / WPF Comparison Whitepaper. This difference makes writing a shared code base difficult at best since the lowest common UI- related base classes are not compatible programmatically. VisualTreeHelper The VisualTreeHelper class allows the developer to examine and work with the visual tree structure. The implementation of this helper class works around the limitation of Silverlight not having a Visual base class. Both WPF and Silverlight contain this helper class; however, they are implemented differently. Method WPF Silverlight FindElementsInHostCoordinates No Yes GetBitmapEffect Yes No GetBitmapEffectInput Yes No GetChild Yes Yes GetChildrenCount Yes Yes GetClip Yes No GetContentBounds Yes No GetDesecendantBounds Yes No GetDrawing Yes No GetEdgeMode Yes No GetEffect Yes No GetOffset Yes No GetOpacity Yes No GetOpacityMask Yes No GetParent Yes Yes GetTransform Yes No GetXSnappingGuidelines Yes No GetYSnappingGuidelines Yes No HitTest Yes No The Silverlight method, FindElementsInHostCoordinates, and the WPF method, HitTest, have similar purposes: to find UI elements that touch a specific point. One difference between the two methods is that Silverlight hit tests are performed using the global coordinate system, while WPF uses the local coordinate system of the specified UI element. To iterate over all the elements under the mouse pointer in a Silverlight application, the following code snippet could be used as a starting point: C# void Page_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { IEnumerable<UIElement> elements; Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 26 of 70 www.wintellect.com
  27. 27. Silverlight / WPF Comparison Whitepaper. elements = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), this); foreach(UIElement item in elements) { // do something. } } VISUAL BASIC Private Sub Page_MouseLeftButtonDown(ByVal sender As Object, _ ByVal e As MouseButtonEventArgs) Dim elements As IEnumerable(Of UIElement) elements = _ VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(Nothing), Me) For Each item As UIElement In elements ' do something. Next End Sub The three shared methods allow developers to query the visual tree for a particular UI element and retrieve its children or parent. CONTROL LIBRARY The following table outlines the various controls provided to WPF and Silverlight, as well as the location where they can be downloaded if not part of the default installation. Table taken from http://msdn.microsoft.com/en-us/library/cc903925(VS.95).aspx). In the case of Silverlight, some controls are available outside the default installation; such as from the Silverlight Toolkit (Toolkit) available at http://www.codeplex.com/silverlight, or the Silverlight SDK (SDK). The Silverlight Toolkit is updated regularly, so checking the web site on a periodic basis is recommended. Control WPF Silverlight AccessText Yes No AdornedElementPlaceholder Yes No AdornerDecorator Yes No AutoCompleteBox No Toolkit Border Yes Yes BulletChrome Yes No BulletDecorator Yes No Button Yes Yes Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 27 of 70 www.wintellect.com
  28. 28. Silverlight / WPF Comparison Whitepaper. ButtonChrome Yes No Calendar Yes SDK Canvas Yes Yes CheckBox Yes Yes ClassicBorderDecorator Yes No ComboBox Yes Yes ComboBoxItem Yes Yes ContentControl Yes Yes ContentPresenter Yes Yes ContextMenu Yes No Control Yes SDK DataGrid Yes SDK DatePicker Yes SDK Decorator Yes No DockPanel Yes Toolkit DocumentPageView Yes No DocumentReference Yes No DocumentViewer Yes No Ellipse Yes SDK Expander Yes Toolkit FixedPage Yes No FlowDocumentPageViewer Yes No FlowDocumentReader Yes No FlowDocumentScrollViewer Yes No Frame Yes No FrameworkElement Yes No Glyphs Yes No Grid Yes Yes GridSplitter Yes SDK GridViewColumnHeader Yes No GridViewHeaderRowPresenter Yes No GridViewRowPresenter Yes No GroupBox Yes No GroupItem Yes No HeaderedContentControl Yes Toolkit HeaderedItemsControl Yes Toolkit HyperlinkButton No Yes Image Yes Yes ImplicitStyleManager Yes Toolkit InkCanvas Yes No InkPresenter Yes Yes ItemsControl Yes Yes ItemsPresenter Yes Yes Label Yes Toolkit Line Yes Yes ListBox Yes Yes Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 28 of 70 www.wintellect.com
  29. 29. Silverlight / WPF Comparison Whitepaper. ListBoxChrome Yes No ListBoxItem Yes No ListView Yes No ListViewItem Yes No MediaElement Yes Yes Menu Yes No MenuItem Yes No MultiScaleImage No Yes NavagationWindow Yes No NumericUpDown No Toolkit Page Yes No PageContent Yes No PageFunction Yes No PasswordBox Yes Yes Path Yes Yes Polygon Yes Yes Polyline Yes Yes Popup Yes Yes ProgressBar Yes Yes RadioButton Yes Yes Rectangle Yes Yes RepeatButton Yes Yes ResizeGrip Yes No Ribbon Yes No RibbonWindow Yes No RichTextBox Yes No ScrollBar Yes Yes ScrollChrome Yes No ScrollContentPresenter Yes Yes ScrollViewer Yes Yes Separator Yes No Slider Yes Yes StackPanel Yes Yes StatusBar Yes No StatusBarItem Yes No SystemDropShadowChrome Yes No TabControl Yes SDK TabItem Yes SDK TabPanel Yes No TextBlock Yes Yes TextBox Yes Yes Thumb Yes Yes TickBar Yes No ToggleButton Yes Yes ToolBar Yes No ToolBarOverflowPanel Yes No Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 29 of 70 www.wintellect.com
  30. 30. Silverlight / WPF Comparison Whitepaper. ToolBarPanel Yes No ToolBarTray Yes No ToolTip Yes Yes Track Yes No TreeView Yes Toolkit TreeViewItem Yes Toolkit UniformGrid Yes No UserControl Yes Yes ViewBox Yes Toolkit Viewport3D Yes No VirtualizingStackPanel Yes No WebBrowser Yes No Window Yes No WindowsFormsHost Yes No WrapPanel Yes Toolkit Note, that even when Silverlight and WPF share a control, they may be implemented differently. For example, in WPF, a Canvas object contain Left, Right, Top, and Bottom dependency properties. In Silverlight, the Canvas object only exposes the Left and Top dependency properties. The Left and Top properties take precedent over the Right and Bottom properties, but worth noting if porting positioning logic from WPF to Silverlight. GENERAL Routed Events There are three types of routed events: direct, bubbling and tunneling. Direct events are those events that are only handled by the element creating the event. Bubbling events are those events that travel upward through the visual tree and can be handled by any parent of the source element. Finally, tunneling events are those events that travel downward through the visual tree and can be handled by any child of the source element. WPF supports all three types of routed events, while Silverlight only supports direct and bubbling events. Additionally, WPF supports the creation of custom routed events via the EventManager helper class. Silverlight currently does not support custom routed events. Data-Binding Data-binding is WPF’s and Silverlight’s mechanism of associating data to controls. Changes to the source data are propagated to the associated controls according to the binding rules set on them. Data can be bound to just about any property on any UI element. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 30 of 70 www.wintellect.com
  31. 31. Silverlight / WPF Comparison Whitepaper. The following snippet of XAML is a simple example of data binding. <TextBlock Text="{Binding Person, Path=FirstName}" /> Binding Modes There are four binding mode available in WPF: One-Way, Two-Way, One-Time, and One-Way To Source.  One-Way binding causes data to flow from the data source to the target element. Changes to the data source will update the target.  Two-Way binding causes data to flow from the data source to the target element, and from the target element back to the data source. Changes to the data source are reflected in the target element, and updates to the target element are propagated back to the data source.  One-Time binding cause data to flow from the data source to the target element. However, the binding does not listen to change notifications, and any changes in the data are not updated in the target element.  One-Way To Source binding causes data to flow from the target element to the data source. Changes in the data source are not propagated to the target element, but changes in the target element are flowed back to the data source. Silverlight does not support the One-Way To Source binding mode. Additionally, the default binding mode, if none is explicitly set, is different between the two platforms. WPF’s default binding mode is dependent upon the dependency property, while Silverlight’s default mode is always OneWay. UpdateSourceTrigger The UpdateSourceTrigger property of the data binding allows the developer to control when the data binding occurs. There are three types of UpdateSourceTriggers:  LostFocus causes the data-binding when the target element loses focus. For example, tabbing out of a TextBox will cause the data-binding to occur.  PropertyChanged causes the data-binding to occur whenever the data changes. For example, typing each key in TextBox will cause the binding to occur.  Explicit trigger will only cause the binding to occur when the UpdateSource method is called on the binding. Silverlight does not support Explicit data-binding. In order to force a data-binding refresh, the property changed event must be fired in the data source, or the UI element must be forced to lose focus. Multi Binding Data binding maps a single data element to a single property of a UI element. MultiBinding allows binding multiple data elements to a single property of a UI element. MultiBinding, unlike Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 31 of 70 www.wintellect.com
  32. 32. Silverlight / WPF Comparison Whitepaper. regular binding, requires the use of a ValueConverter, or more specifically, a MultiValueConverter. To demonstrate the MultiValueConverter, a simple, contrived, example is needed. The XAML below declares a TextBlock with a MultiValueConverter and two bindings: <TextBlock> <TextBlock.Text> <MultiBinding Converter="{StaticResource NameConverter}"> <Binding Source="{StaticResource Person}" Path="FirstName" /> <Binding Source="{StaticResource Person}" Path="LastName" /> </MultiBinding> </TextBlock.Text> </TextBlock> And the corresponding MultiValueConverter: C# public class NameConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { // Assuming first and last names are passed in. return string.Concat(values[0], " ", values[1]); } // ConvertBack method snipped for brevity. … } VISUAL BASIC Public Class NameConverter Implements IMultiValueConverter Public Function Convert(ByVal values() As Object, _ ByVal targetType As System.Type, _ ByVal parameter As Object, _ ByVal culture As System.Globalization.CultureInfo) As Object _ Implements System.Windows.Data.IMultiValueConverter.Convert ' Assuming first and last names are passed in. Return String.Concat(values(0), " ", values(1)) End Function ' ConvertBack method snipped for brevity. … End Class Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 32 of 70 www.wintellect.com
  33. 33. Silverlight / WPF Comparison Whitepaper. It would be remiss not to mention a simpler solution to this problem in WPF. With Service Pack 1 of WPF 3.5, the StringFormat property has been added to bindings. The above XAML could be rewritten, without the use of a MultiValueConverter, as: <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0} {1}"> <Binding Source="{StaticResource Person}" Path="FirstName" /> <Binding Source="{StaticResource Person}" Path="LastName" /> </MultiBinding> </TextBlock.Text> </TextBlock> WPF supports multiple data-binding while Silverlight only allows binding to single value. However, a viable work-around in Silverlight would be to create a custom class to aggregate the multiple data elements into a single property and either parse them in the Value Converter or use the composite value directly. For example, C# public class Person : INotifyPropertyChanged { private string _firstName; private string _lastName; public event PropertyChangedEventHandler PropertyChanged; public string FirstName { get { return _firstName; } set { _firstName = value; NotifyPropertyChanged("FirstName"); NotifyPropertyChanged("FullName"); } } public string LastName { get { return _lastName; } set { _lastName = value; NotifyPropertyChanged("LastName"); NotifyPropertyChanged("FullName"); } } public string FullName { Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 33 of 70 www.wintellect.com
  34. 34. Silverlight / WPF Comparison Whitepaper. get { return _firstName + " " + _lastName; } } private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { try { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } catch (Exception ex) { // Error handing snipped. } } } } VISUAL BASIC Public Class Person Implements INotifyPropertyChanged Private _firstName As String Private _lastName As String Public Event PropertyChanged As PropertyChangedEventHandler _ Implements INotifyPropertyChanged.PropertyChanged Public Property FirstName() As String Get Return _firstName End Get Set(ByVal value As String) _firstName = value NotifyPropertyChanged("FirstName") NotifyPropertyChanged("FullName") End Set End Property Public Property LastName() As String Get Return _lastName End Get Set(ByVal value As String) _lastName = value NotifyPropertyChanged("LastName") NotifyPropertyChanged("FullName") End Set End Property Public ReadOnly Property FullName() As String Get Return _firstName & " " & _lastName Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 34 of 70 www.wintellect.com
  35. 35. Silverlight / WPF Comparison Whitepaper. End Get End Property Private Sub NotifyPropertyChanged(ByVal propertyName As String) Try RaiseEvent PropertyChanged(Me, _ New PropertyChangedEventArgs(propertyName)) Catch ex As Exception ' Omitting error handling for brevity. End Try End Sub End Class By binding on FullName, Silverlight will receive a change notification whenever either the FirstName or LastName properties change. Element Binding WPF supports binding to other elements within the visual tree. The following is perfectly legal in a WPF application: <TextBox x:Name="Field1" /> <TextBlock Text="{Binding ElementName=Field1, Path=Text}" /> Silverlight 3 Note Element-to-element binding will be supported in Silverlight 3. Data Providers While the source object can be any .Net object, WPF provides some specialized data providers to enhancing the binding experience. The XmlDataProvider and the ObjectDataProvider are two such data providers. Silverlight, on the other hand, does not provide an implementation of the ObjectDataProvider. However, since the source object can be any .Net object, programming around the deficiency is not difficult in Silverlight. The lost functionality, such as binding to a method, can be achieved by wrapping the method in a property and implementing the INotifyPropertyChanged interface judiciously. Networking Communications Silverlight does not have the capability of making a synchronous networking request due to the potential of blocking the main UI thread. Silverlight can only make asynchronous network calls. WPF has access to the complete networking stack within the .Net Framework and does not have this restriction. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 35 of 70 www.wintellect.com
  36. 36. Silverlight / WPF Comparison Whitepaper. In addition to HTTP communications, Silverlight also can communicate to network resources via socket programming. Socket development provides interfaces for developers who require a more tightly controlled access to the network. HTTP Communications Support for HTTP communication opens the door to several options within Silverlight; web services, WCF Services, and REST. Note that Silverlight is still bound to the supported bindings listed below in the BINDINGS section. SOAP Silverlight supports SOAP 1.1 over HTTP, and does not support other versions of SOAP, or other web services not compliant with WS-I Basic Profile 1.0. Silverlight only supports textual XML encoding, but not binary encoding. Silverlight 3 Note Silverlight 3 will support binary encoding WPF can support all SOAP versions and multiple encoding types. Fault Handling Silverlight cannot currently natively handle SOAP Fault Exceptions due to web browser limitations. When a fault does occur, an exception is thrown, but does not specify any detail about the fault. In essence, Silverlight can determine a fault happened, but not why it happened. Silverlight 3 Note Silverlight 3 will implement a solution to provide more detailed information about SOAP exceptions. Concurrent Connections Silverlight is bound to the browsers networking stack and is limited to its concurrent connection settings. The most restrictive of these limits is two concurrent connections, but is dependent on the system’s maximum network connections. This setting can be changed in the registry under the following key: HKEY_LOCAL_MACHINE/ (or HKEY_CURRENT_USER) SOFTWARE/ Microsoft/ Internet Explorer/ MAIN/ FeatureControl/ FEATURE_MAXCONNECTIONSPERSERVER WPF has no such restriction and is free to open as many concurrent connections as needed within system limitations. Programmatic Differences Between Silverlight and WPF – A Whitepaper Page 36 of 70 www.wintellect.com

×