This article not only explains the theory aspect of WPF and Silverlight, but also shows small samples for each of them.
Video demonstration One Way, Two Way, and One Time Bindings using Silverlight
This article talks about 21 important FAQs from the perspective of WPF and Silverlight. Both these technologies are connected to a certain extent. This article not only explains the theory aspect of these technologies, but also shows small samples for each of them.
Here’s a complete free e-book covering 400 FAQ for C#, SQL Server, WPF, WWF, WCF, and a lot more. Feel free to download it and enjoy!
What is the Need for WPF when we have GDI, GDI+, and DirectX?
First, let’s try to understand how Microsoft display technologies have evolved:
Note: Hardware acceleration is a process in which we use hardware to perform some functions rather than performing those functions using software running in the CPU.
WPF is a collection of classes that simplifies building dynamic user interfaces. Those classes include a new set of controls, some of which mimic old UI elements (such as
Button), and some that are new (such as
- User32: This provides the Windows look and feel for buttons and textboxes and other UI elements. User32 lacked drawing capabilities.
- GDI (Graphics Device Interface): Microsoft introduced GDI to provide drawing capabilities. GDI not only provides drawing capabilities, but also a high level of abstraction on hardware display. In other words, it encapsulates all complexities of hardware in the GDI API.
- GDI+: GDI+ was introduced which basically extends GDI and provides extra functionalities like JPG and PNG support, gradient shading, and anti-aliasing. The biggest issue with the GDI API was it did not use hardware acceleration and did not have animation and 3D support.
- DirectX: The biggest issues with GDI and its extension GDI+ are hardware acceleration and animation support. This came as a big disadvantage for game developers. To answer and serve game developers, Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D, full color graphics, media streaming facility, and lots more. This API did not mature in the gaming industry.
- WPF: Microsoft had 3 to 4 different APIs for display technologies, so why one more? DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to develop UI elements like textboxes, buttons, grids, etc., using the DirectX technology by which they could exploit the hardware acceleration feature. As WPF stands on top of DirectX, you can not only build simple UI elements but also go one step further and develop special UI elements like
Ellipse. Oh yes, you can go one step further and build animations. WPF is not meant for game development. DirectX still will lead in that scenario. In case you are looking for light animation (not game programming), WPF will be a good choice. You can also express WPF using XML which is also called as XAML. In other words, WPF is a wrapper built over DirectX. Let’s now define WPF.
How Does Hardware Acceleration Work with WPF?
Hardware acceleration is a process in which we use hardware to perform some functions rather than performing those functions using software running in the CPU.
WPF exploits hardware acceleration in a two tier manner.
The WPF API first detects the level of hardware acceleration using parameters like RAM of video card, per pixel value, etc. Depending on that, it uses a Tier 0, Tier 1, or Tier 2 rendering mode.
- Tier 0: If the video card does not support hardware acceleration, then WPF uses the Tier 0 rendering mode. In other words, it uses software acceleration. This corresponds to the working of DirectX versions less than 7.0.
- Tier 1: If the video card supports partial hardware acceleration, then WPF uses the Tier 1 rendering mode. This corresponds to working of DirectX versions between 7.0 and 9.0.
- Tier 2: If the video card supports hardware acceleration, then WPF uses the Tier 2 rendering mode. This corresponds to working of DirectX versions equal or greater than 9.0.
Does that Mean WPF has Replaced DirectX?
No, WPF does not replace DirectX. DirectX will still be needed to make cutting edge games. The video performance of DirectX is still many times higher than the WPF API. So when it comes to game development, the preference will always be DirectX and not WPF. WPF is not an optimum solution to make games. Oh yes, you can make a tic tac toe game with it but not high action animation games.
One point to remember: WPF is a replacement for Windows Forms and not DirectX.
Can We Define WPF in a Precise Way?
Windows Presentation Framework is the new presentation API. WPF is a two and three dimensional graphics engine. It has the following capabilities:
- Has all equivalent common user controls like buttons, check boxes, sliders, etc.
- Fixed and flow format documents
- Has all of the capabilities of HTML and Flash
- 2D and 3D vector graphics
- Data binding
What is XAML?
XAML (pronounced as Zammel) is a declarative XML-based language by which you can define objects and properties in XML. A XAML document is loaded by a XAML parser. The XAML parser instantiates objects and sets their properties. XAML describes objects, properties, and the relations between them. Using XAML, you can create any kind of objects, graphical or non-graphical. WPF parses the XAML document and instantiates the objects and creates the relations defined by the XAML. So XAML is an XML document which defines objects and properties and WPF loads this document in actual memory.
So is XAML Meant Only for WPF?
No, XAML is not meant only for WPF. XAML is an XML-based language and it has several variants.
- WPF XAML is used to describe WPF content, such as WPF objects, controls, and documents. In WPF XAML, we also have XPS XAML which defines an XML representation of electronic documents.
- Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a cross-platform browser plug-in which helps us create rich web content with two-dimensional graphics, animation, and audio and video.
- WWF XAML helps us describe Windows Workflow Foundation content. The WWF engine then uses this XAML and invokes the workflow accordingly.
Can You Explain the Overall Architecture of WPF?
The above figure shows the overall architecture of WPF. It has three major sections: presentation core, presentation framework, and Milcore. In the same diagram, we can see how other sections like DirectX and Operating System interact with the system. So let’s go section by section to understand how everything works.
- User32: It decides what goes where on the screen.
- DirectX: As said previously, WPF uses DirectX internally. DirectX talks with drivers and renders the content.
- Milcore: Mil stands for media integration library. This section is unmanaged code because it acts like a bridge between the WPF managed and the DirectX / User32 unmanaged API.
- Presentation core: This is a low level API exposed by WPF providing features for 2D, 3D, geometry, etc.
- Presentation framework: This section has high level features like application controls, layouts, content, etc., which helps you build up your application.
Which Are the Different Namespaces and Classes in WPF?
There are ten important namespaces / classes in WPF.
All WPF objects derive from
DispatcherObject. WPF works on an STA model, i.e., Single Threading Apartment model. The main duty of this object is to handle concurrency and threading. When messages like mouse clicks, button clicks, etc., are initiated, they are sent to the
DispatcherObject which verifies whether code is running on the correct thread. In the coming sections, we will look in detail how WPF threading works.
When WPF was designed, a property based architecture was considered. In other words, rather than using methods, functions, and events, object behavior will interact using properties. For now, we will only restrict ourselves to this definition. In the coming sections, we have dedicated questions for this.
Visual class is a drawing object which abstracts drawing instructions, how drawing should be done like clipping, opacity, and other functionalities. The
Visual class also acts like a bridge between the unmanaged MilCore.dll and the WPF managed classes. When a class is derived from
Visual, it can be displayed on Windows. If you want to create your own customized user interface, then you can program using
UIElement handles three important aspects: layout, input, and events.
FrameWorkElement uses the foundation set by
UIElement. It adds key properties like
VerticalAlignment, margins, etc.
This class helps us create basic shapes such as rectangle, polygon, ellipse, line, and path.
This class has controls like
ListBox, etc. It adds some extra properties like font, foreground and background colors.
It holds a single piece of content. This can start from a simple label and go down to a unit level of string in a layout panel using shapes.
This is the base class for all controls that show a collection of items, such as the
This class is used for all layout containers—elements that can contain one or more children and arrange them as per specific layout rules. These containers are the foundation of the WPF layout system, and using them is the key to arranging your content in the most attractive and flexible way possible.
The Different Elements Involved in WPF Application
In order to understand the different elements of WPF, we will do a small ‘
hello world’ sample and in that process, we will understand the different elements of WPF.
Note: For this sample, we have VS 2008 Express edition.
Start VS 2008 Express and from Templates, select WPF Application as shown in the figure below:
Once we have created the WPF Application project, you will see two file types: the XAML file and the behind code, i.e., XAML.cs. XAML files are nothing but XML files which have all the elements needed to display the window's UI. Every XAML element maps to some class. For instance, the
Window element maps to the
Button elements in the XAML file map to a
System.Windows.Control.Button class, and the
Grid XAML elements map to
App.XAML and App.XAML.CS are the entry point files. If we you look at the code for App.XAML.CS, you will see a reference to the XAML file which needs to be loaded. The first code which runs in the application is the
void main() method from App.XAML.CS which in turn loads the Window1.XAML file for rendering.
We can now connect the behind code method and functions to the events in the XAML file elements.
You can see from the above code snippet how the
Button element has the
Click event linked to the
MyButton_Click is the method which is in the XAML.CS behind code. So now if you run the code, you can see the button and if you click on it, you can see the message box.
What Are Dependency Properties?
Dependency properties belong to one class but can be used in another. Consider the code snippet below:
<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" />
Width are regular properties of the
Canvas.Left are dependency properties as they belong to the
Canvas class. It is used by the
Rectangle to specify its position within
Are XAML Files Compiled or Built at Runtime?
XAML files are usually compiled rather than parsed at runtime. But they also support parsing during runtime. When we build a XAML based project, you will see it creates a g.cs extension in the obi\Debug folder. Therefore, for every XAML file, you will find a g.cs file. For instance, a Shiv.XAML will have a Shiv.g.cs file in the obi\Debug folder. In short, at runtime, you actually do not see the XAML file. But if you want to do runtime parsing of a XAML file, it also allows that to be done.
Can You Explain How We Can Separate Code and XAML?
This is one of the most important features of WPF, separating the XAML from the code to be handled. So designers can independently work on the presentation of the application and developers can actually write the code logic independent of how the presentation is.
Figure 16.1: XAML and behind code in action
Above is a code snippet which shows a XAML file and the code completely detached from the XAML presentation. In order to associate a class with a XAML file, you need to specify the
x:Class attribute. Any event specified on the XAML object can be connected by defining a method with sender and event values. You can see from the above code snippet that we have linked
MyClickEvent to an event in the behind code.
Note: You can find a simple sample in the WindowsSimpleXAML folder. Feel free to experiment with the code… experimenting will teach you more than reading something theoretical.
How Can We Access XAML Objects in Behind Code?
To access XAML objects in behind code, you just need to define them with the same name as given in the XAML document. For instance, in the below code snippet, we have named the object as
objtext and the object is defined with the same name in the behind code.
Figure 16.2: Accessing a XAML object
Note: You can get the source code from the WindowsAccessXAML folder.
What is Silverlight?
Silverlight is a web browser plug-in by which we can enable animations, graphics, and audio/video. You can compare Silverlight with Flash. We can view animations with Flash and it’s installed as a plug-in in the browser.
Can Silverlight Run on Platforms Other Than Windows?
Yes, animations made in Silverlight can run on platforms other than Windows. In whatever platform you want to run, you just need the Silverlight plug-in.
Come On, Even WPF Runs Under Browser, Why Silverlight?
Yes, there is something called as a WPF browser application which can run WPF in the browser. For a WPF browser application, you need the .NET Framework to be installed in the client location while for Silverlight, you need only the plug-in. So in other words, WPF browser applications are OS dependent while Silverlight is not. A Silverlight plug-in can run in OSs other than Windows while we all know the .NET Framework only runs in Windows.
What is the Relationship between Silverlight, WPF, and XAML?
As explained previously, XAML is an XML file which defines UI elements. This XML file can be read by the WPF framework or Silverlight framework for rendering. Microsoft first developed WPF and they used XAML files to describe UI elements to the WPF framework. Microsoft then extended WPF and made WPF/e which helped to render the UI in the browser. WPF/e was the code name for Silverlight. Later Microsoft launched Silverlight officially. So the XAML just defines the XML structure to represent UI elements. Both the frameworks, i.e., WPF and Silverlight, then read the UI elements and render the UI elements in the respective platform.
Can You Explain the Silverlight Architecture?
So we can visualize the Silverlight architecture as a combination of some functionalities from the core .NET framework, AJAX, and some functionalities like animation, media, etc., provided by the core Silverlight framework. We can think of the Silverlight architecture as a combination of four important blocks:
- Some .NET Framework components: Silverlight uses some components from the .NET Framework. One of the main components is WPF. Many UI components (
textbox, etc.), XAML parsing, etc., are taken from the core WPF system. It also has taken components like WCF to simplify data access. It has CLR for memory management, safety checking, and garbage collection. The base class libraries of .NET are used for string manipulation, algorithms, expressions, collections, and globalization.
- Presentation core: The core presentation framework has functionalities to display vector 2D animations, images, media, DRM, and handles input like mouse and keyboard.
What Are the Various Steps to Make a Simple Silverlight Application?
This sample we are making using VS 2008 Web Express edition and .NET 3.5. It’s a six step procedure to run our first Silverlight application. So let’s go through it step by step.
For this example, we have selected the first option. Once you click OK, you should see the full IDE environment for Silverlight.
So let’s run through some basic points regarding the IDE view that we see. You will see there are two projects: your web application and the Silverlight application. In the Silverlight application, we have two XAML files: App.XAML and Page.XAML. App.XAML has the global level information.
Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>
We also need to refer to the
ScriptManager from the Silverlight name space. The
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
Finally, we need to refer to the Silverlight application. You can see that in the source we have referred to the XAP file. The XAP file is nothing but a compiled Silverlight application which is compressed and zipped. It basically has all the files that are needed for the application in a compressed format. If you rename the file to a ZIP extension, you can open it using WinZIP.
<asp:Silverlight ID="Xaml1" runat="server"
MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
So your final ASPX / HTML code consuming the Silverlight application looks something as shown below:
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
<form id="form1" runat="server" style="height:100%;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Silverlight ID="Xaml1" runat="server"
MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
- Step 1: The first thing we need to do is install the Silverlight SDK kit from http://www.microsoft.com/downloads/details.aspx?familyid=FB7900DB-4380-4B0F-BB95-0BAEC714EE17&displaylang=en.
- Step 2: Once you install the Silverlight SDK, you should be able to use the Silverlight template. So when you go to create a new project, you will see a ‘SilverLight Application’ template as shown in the below figure:
- Step 3: Once you click OK, you will see a dialog box as shown below, which has three options:
- Add an ASP.NET web project to the solution to host Silverlight: This option is the default option, and it will create a new Web Application project that is configured to host and run your Silverlight application. If you are creating a new Silverlight application, then this is the option to go.
- Automatically generate a test page to host Silverlight at build time: This option will create a new page at runtime every time you try to debug and test your application. If you want to only concentrate on your Silverlight application, then this option is worth looking at.
- Link this Silverlight control into an existing website: If you have an existing Silverlight application, then this option helps to link the Silverlight application with the existing web application project. You will not see this option enabled in new projects, you need to have an existing web application.
- Step 4: Now for simplicity's sake, we just use the
TextBlock tag to display a text. You can see that as we type in Page.XAML, it is displayed in the viewer.
- Step 5: Now we need to consume the Silverlight application in an ASPX page. So in the HTML / ASPX page, we need to first refer to the Silverlight namespace using the
- Step 6: So finally set the web application as Start up and also set this page as Start up and run it. You should be pleased to see your first Silverlight application running.
Other Silverlight FAQ
- 24th March, 2009: Initial version