In this I am going to start talking about Windows Presentation Foundation or WPF in short. I hope you guys find this series interesting and informative.
So once you have decided to Learn WPF do not a step back or leave it in between because once learn the full power of WPF you would know how to create windows and web applications with awesome graphics easily.
What is WPF
At the very basic level WPF is just a framework which is used for building Windows application. Before WPF the windows applications majorly used couple of dlls (User32 and GDI32). These were the 32 bit versions of their 16 bit parents who were introduced in mid 1980s. Now if you have worked in Windows Forms you would know that the interface that you used to create an application were just a wrapper around these dlls.
Why to Use WPF
But WPF does not use GDI32 and barely uses USER 32. It’s not just a wrapper around these dlls. WPF was introduced as part of .NET 3.0 framework. It contains both managed and unmanaged code. It was designed from scratch so that .NET languages could be used to program in WPF. You would need to use .NET to use WPF as these are no public unmanaged API offered for this. This provides a lot of advantages as you don’t have to struggle with the issues you face using a wrapper around the unmanaged code. You need to be either on XP SP3, Vista, Windows 2003 or above to use WPF.
You might still be wondering as to what’s the thinking behind creating a new framework such as WPF when we already have a Windows Forms for creating a Windows application which is used by lot of people and huge numbers of people are skilled in it. The reason is Microsoft did not want to lag behind after all the thinking and market changes that have happened since the initial framework for creating windows application was launched and was really hard to keep the future versions compatible with it ancestors. As whenever an upgrade happens to a new version, people expect it to be really smooth. At the time when the initial Windows application development architecture was designed then the computer was not capable of so much processing power or graphical capabilities. Nowadays the computer hardware capabilities have progressed in leaps and bounds. So there was a need to design a framework that could utilize that capability. WPF provide the interface using which could design rich graphical user applications without having to deal with complexity of the directx or OpenGL code. Now the old dlls that were used in creating WPF application does not provide any way of utilizing the directx capability unless you are ready to program in directx or OpenGL.
WPF is also auto scalable by default which means that if you run you WPF application on machine with different DPIs you application will automatically scale its contents according to the DPI and resolution of the machine. You can simply see that in action by simply creating a WPF application and zooming into it. If you zoom into other applications or graphics in your system you see it getting pixelated but with WPF you will not see that.
As the times have changed, people’s expectations from the applications have changed. A decade ago people were okay with console application running on their computers but today they want a rich and cool user interface to work with. The games that we see now have reached that level and same can be achieved for windows application using WPF. You can make your complete application be blended into a single theme that you want, like your company logo colors, etc.
It was easy to make websites carry branding before using HTML as anyone without any programming experience can also use HTML to make a nice looking website which corresponds to your company. WPF also utilizes the power of Markup to give the designer the ability to do more and be part of the graphical interface easily. The use of markup makes the Windows apps move forward to the level of web apps styling easily.
Now in today’s time we do have the option to create a visually appealing application but the problem is to integrate all those component together that make that visually appealing application. We do have HTML for Web, Win32 with easy interface for Windows applications, DirectX or OpenGL for developing rich graphics application and Flash for designing rich vector graphics but all these have different capabilities and it’s really difficult to integrate all of them together. But WPF provides us with a single integrated solution for it. The capabilities that WPF provides are already available with the technologies I mentioned before but the advantage with WPF is that it provides all these capabilities at one place and integrated.
As you could see in the image below the basic architecture of WPF is designed with directx at its base above kernel.
WPF utilizes the 3D hardware your system to render 3D or 2D graphics on your system. On top of Directx level is the most basic component of WPF called as the Media Integration Layer or MIL. This is the component that takes the various types of media like the bitmaps, images, videos, etc and renders them all into a single directx surface. This MIL is unmanged code because it has to talk to directx and there need to be lot of calls need to be made to the com interface while dealing with directx and directx uses a lot com calls as they are cheap in its context but when you come to .Net code that is not the case. Using com from needs you to go through the interop layer and made thousands of call through the interop layer wil burn a lot of CPU cycle. So that’s the advantage to MIL, as to render a complex shape you make just one interop call to MIL and MIL then internally makes thousand and hundreds of com calls to DirectX to render that shape. Above the MIL we have two dlls for WPF. Presentation Core and Presentation framework. Presentation core is the public face of the MIL, it provides the .NET API that exposes he rendering services of the MIL. Above this presentation core we have the Presentation Framework layer that provides the high level services. Presentation layer provides the concept of Controls, layouts, data binding, animations, etc. As a WPF developer you would be spending most your time with Presentation framework. And you would be using the Presentation Core at the time graphics programming. The reason for separation of these layers is to make the rendering available without being dependent on WPF features.
What is XAML (Extensible Application Markup Language)
When you create a WPF application you would see two code files in your project. One is the regular .cs or .vb file which is your standard code file and the other one is you XAML file which is something new to WPF. Now a XAML file looks a lot like a XML file. Now if you would have created a WPF application in the past then you would have seen XAML. I would like clarify here that XAML is independent of WPF and WPF is independent of XAML. They are separable. XAML is nothing but a language to create .NET objects and this means we could what we do XAML in C# or VB code as well. It’s on you to decide what to use when. So if you see the image below you would find XAML and its corresponding C# code.
Now XAML uses the type converter infrastructure to map the string and integer values to map to the property values at the run time. And it also XAML in knows as to what does the content contain. The most simple and important thing about XAML is that it creates objects and sets properties. Also when you create a WPF application and open any of the XAML files you would see something like this at the top of it.
This is simply references to the namespaces so that you could use the components in that namespace. If you are referencing any namespaces in xaml then this is the place to add them. Microsoft took a long time in developing xaml and figuring out how xaml does what it actually does.
UI Tree in WPF
The XAML interface objects are built as trees of objects. As you would see in the code below,
Here we have root element which is a Window. This Window contains a single child which is Grid. The grid contains other children and it’s the Grid job to assign as to where these children are placed in the layout. So you see a tree root structure.
WPF provides two tree structures: The Logical Tree and The Visual Tree. The visual tree will be of use if you are concentrating on the presentation. The Visual Tree is simply the super set of the logical tree. You can see below that all the children of the logical tree are present in the visual tree. So these two trees are the different views of the same set of the objects that make up the UI. The logical tree provides you with the detail to focus on the core structure of the User Interface and to ignore the details of how exactly it is presented.
Events and Commands in WPF
There are two ways for handling input in a WPF application: Events and Commands.
Events are very closely tied into the visual tree. Any Mouse or keyboard inputs originate from an element. The one with the focus – keyboard input and the one with the stylus – mouse inputs. As we have already seen that the visual tree was pretty complex for just a couple of elements, you could imagine the complexity if there are a lot of controls in your visual tree. It would become all the more complex if you add an event handler to every element of the visual tree to receive the inputs.
To save us from this complexity WPF has Event routing. Event routing allows the ancestor of the element to handle the event. Now there are two types of routing in WPF – Tunneling and Bubbling.
Tunneling starts from the root of the visual tree and goes through the tree and reaches the element to which the event is targeted. Generally Preview events are the ones that tunnels. Bubbling Event works in the opposite direction. It starts from the Element and goes up the parent to the root. Main events are the one that bubbles. The concept behind providing a preview is to give the parent element a chance to handle the originating event.
For example if you have a button in the Grid and you want to handle the Mouse down event. Now if you want Grid to handle the event before the Button does you need to use the Preview events (PreviewMouseDown) and if you want the button to handle the event first then you should use the main event (MouseDown).
Commands on the other hands help you do the same action through multiple inputs like a keyboard shortcut, stylus gesture, menu clicks, button clicks, etc. So that multiple inputs can use the same command if they want same job to be accomplished.
Controls in the previous versions like Windows forms correspond to behavior as well and presentation of an element, whereas in WPF controls are a bit different. Let’s take a Button for Example, a button has a click event which is an API feature related to the user interaction. It also supports the content Model for composition which is also an API feature. It supports Focus which is an interactivity feature. It can be associated with Command which is again an API feature. It also supports the Automation API which makes it accessible to screen reader, automation testing, etc. But there one thing that a WPF button cannot do which its activex, Win32 counterparts can.
A WPF button is a lookless control which means it has no intrinsic look and it does not know how to present itself. The look of a control in WPF is controlled a distinct entity known as Template. So button may look like a circle or a star but it will still support all the API and interaction features. Let see how this works in code.
Use the following code in a WPF application and you would be able set the template property for the button control.
You should notice a few things about the code above.
- We have defined a ControlTemplate for the Button which changes the look and feel of the Button.
- The Fill property of the Rectangle in the ControlTempalate is done using the TemplateBinding with Background. What this does is binds the Fill of the rectangle to the Background of the Button. So whatever background we set on the Button becomes the Fill of the rectangle.
- You would also see Curly braces around the TemplateBinding which signifies that it a special property. This is considered to be Markup extension. Markup extension signifies that it would be decided at runtime as how this property will work. This syntax means that we need to create an instance of the TemplateBinding Class with Background as a string and a constructor parameter and WPF expects the whole thing inside the curly braces to derive from Markup extension base class. Now this Base class provides an abstract method named Provide Value. This method would be called at runtime to decide what value will the Fill property have a runtime. A custom markup extension can build depending on what we need.
- You would also see the same thing as Rectangle Fill Property for TextBlock Text Property.
Lets change the code to look something like below:
You would now notice that the Content of the Button is now and Ellipse and to make that as the content of the button we need to need to use a ContentPresenter instead of a TextBlock because a TextBlock is a primitive control and it could only display text. So to display the any content we need to use the ContentPresenter and TemplateBind the Content property. So if we want any other content we could do that now.
Primitive Elements in WPF
As you have seen that the controls do not define their own look, so are you not wondering as to how do anything appear. Just as we saw above a button control derives its look from its template, and the controls derive their appearance from there templates so is there an infinite loop to look for the template?
That’s not the case. Only the controls have a template and most elements in WPF are not controls. Only the Controls that derive from the Controls Base class are supposed to have some kind of interactive behavior. Examples of controls are Button, TreeView, ListBox, TextBox, etc. Only the Controls derived from the Controls class have a template because it’s the Control class that introduces the template property.
Examples of Elements are Rectangle, Ellipse, Image, TextBlock etc. These do not derive from Controls and are more primitive and derived from FramworkElement (Base class for Controls as well). These elements do not have a template of their own and as they are more primitive and there presentation is specifically designed. Primitive elements are the one that provide an intrinsic appearance for them. These can be also considered to be lookful controls. Primitive elements do not have any intrinsic behavior of their own and you have to add the events and handler to get some interactive behavior from them.
You might note that a lot of elements that do not derive from the Control Class are placed in the namespace System.Windows.Control. This is confusing you should keep in mind that the Elements that derive from the Control Class are Controls.
Layout in WPF
The new and useful feature in WPF is the Layout primitive also known as Panels in have. The Panles are required at places where we need to position multiple childrens. The panels available in WPF are Grid (Advanced table/grid-based layout), Canvas (Fixed layout, supports anchoring), StackPanel (left to right and top to bottom layout), DockPanel (Docking layout) and WrapPanel (Flow-like formatting).
Flowed Text in WPF
WPF provides a flow layout for the text so that the text fits into whatever space is available. A Flow document has a HTML-like feature set and it has reader controls.
In a flow document we can integrate any mixture of text styles, user interface elements, HTML features (Lists, floating data, etc). WPF makes it much easier to render text in columns than HTML which is very useful because columns allow shorter line lengths which improves reading speed.
Data Binding in WPF
When you come across data binding you would think about databases or collections but in WPF databinding has much broader scope. Data Binding can be used at times when you want to present any data to the screen. WPF data binding either connects to objects or xml. WPF never assumes the presence of a database. Infact you never use data binding directly with database. You load the data from the database into your domain objects, datasets, etc and then data binding presents them on screen.
Data Binding brings up a very interesting concept in WP Known as DataTemplate. Similar to ControlTempalate which defines how a control should look like, DataTemplate defines how the data should look like. So you define the template for a particular class of application and the template can be used to present the data on the screen.
Its because of the power of Data Template that WPF does not contain a DataGrid as you could define how the data should be presented on screen.
There are multiple ways in WPF to deploy the application to the user machine:
- Build a MSI installer
- Click Once deployment but is supported only in full trust environment.
- XBAP – XAML Browser application. This is like the Click once but imparts the experience like the java applet style. This does not require full trust as it runs in browser.
- .NET 3.5 SP1 deployment options
- Client only framework – option to deploy only a part of the framework. Can be deployed in following ways:
- Setup bootstrapper – this installs the framework before going to the normal windows setup
- Deploy via Click Once
- Client only framework – option to deploy only a part of the framework. Can be deployed in following ways:
The code for this post can be downloaded here.
Any questions, Comments and feedback are most welcome.