Monday, November 23, 2015

WPF - Overview

WPF stands for Windows Presentation Foundation. It is a powerful framework for building Windows applications. This tutorial explains the features that you need to understand to build WPF applications and how it brings a fundamental change in Windows applications.
WPF was first introduces in .NET framework 3.0 version, and then so many other features were added in the subsequent .NET framework versions.

WPF Architecture

Before WPF, the other user interface frameworks offered by Microsoft such as MFC and Windows forms, were just wrappers around User32 and GDI32 DLLs, but WPF makes only minimal use of User32. So,
  • WPF is more than just a wrapper.
  • It is a part of the .NET framework.
  • It contains a mixture of managed and unmanaged code.
The major components of WPF architecture are as shown in the figure below. The most important code part of WPF are −
  • Presentation Framework
  • Presentation Core
  • Milcore
WPF Architecture
The presentation framework and the presentation core have been written in managed code. Milcore is a part of unmanaged code which allows tight integration with DirectX (responsible for display and rendering). CLR makes the development process more productive by offering many features such as memory management, error handling, etc.

WPF – Advantages

In the earlier GUI frameworks, there was no real separation between how an application looks like and how it behaved. Both GUI and behavior was created in the same language, e.g. C# or VB.Net which would require more effort from the developer to implement both UI and behavior associated with it.
In WPF, UI elements are designed in XAML while behaviors can be implemented in procedural languages such C# and VB.Net. So it very easy to separate behavior from the designer code.
With XAML, the programmers can work in parallel with the designers. The separation between a GUI and its behavior can allow us to easily change the look of a control by using styles and templates.

WPF – Features

WPF is a powerful framework to create Windows application. It supports many great features, some of which have been listed below −
FeatureDescription
Control inside a ControlAllows to define a control inside another control as a content.
Data bindingMechanism to display and interact with data between UI elements and data object on user interface.
Media servicesProvides an integrated system for building user interfaces with common media elements like images, audio, and video.
TemplatesIn WPF you can define the look of an element directly with a Template
AnimationsBuilding interactivity and movement on user Interface
Alternative inputSupports multi-touch input on Windows 7 and above.
Direct3DAllows to display more complex graphics and custom themes

WPF - Environment Setup

Microsoft provides two important tools for WPF application development.
  • Visual Studio
  • Expression Blend
Both the tools can create WPF projects, but the fact is that Visual Studio is used more by developers, while Blend is used more often by designers. For this tutorial, we will mostly be using Visual Studio.

Installation

Microsoft provides a free version of Visual Studio which can be downloaded fromVisualStudio.
Download the files and follow the steps given below to set up WPF application development environment on your system.
  • After the download is complete, run the installer. The following dialog will be displayed.
Installer
  • Click the Install button and it will start the installation process.
Installation Process
  • Once the installation process is completed successfully, you will get to see the following dialog box.
Dialog Box
  • Close this dialog box and restart your computer if required.
  • Now open Visual Studio from the Start Menu which will open the following dialog box.
Visual Studio
  • Once all is done, you will see the main window of Visual Studio.
Window of Visual Studio
You are now ready to build your first WPF application.

WPF - Hello World

In this chapter, we will develop a simple Hello World WPF application. So let’s start the simple implementation by following the steps given below.
  • Click on File > New > Project menu option.
Project menu option
  • The following dialog box will be displayed.
New Project dialog box
  • Under Templates, select Visual C# and in the middle panel, select WPF Application.
  • Give the project a name. Type HelloWorld in the name field and click the OK button.
  • By default, two files are created, one is the XAML file (mainwindow.xaml) and the other one is the CS file (mainwindow.cs)
  • On mainwindow.xaml, you will see two sub-windows, one is the design window and the other one is the source (XAML) window.
  • In WPF application, there are two ways to design an UI for your application. One is to simply drag and drop UI elements from the toolbox to the Design Window. The second way is to design your UI by writing XAML tags for UI elements. Visual Studio handles XAML tags when drag and drop feature is used for UI designing.
  • In mainwindow.xaml file, the following XAML tags are written by default.
<Window x:Class = "HelloWorld.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "604">
 
   <Grid> 
   </Grid> 
 
</Window> 
  • By default, a Grid is set as the first element after page.
  • Let’s go to the toolbox and drag a TextBlock to the design window.
ToolBox
  • You will see the TextBlock on the design window.
TextBlock
  • When you look at the source window, you will see that Visual Studio has generated the XAML code of the TextBlock for you.
  • Let’s change the Text property of TextBlock in XAML code from TextBlock to Hello World.
<Window x:Class = "HelloWorld.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "604"> 
 
   <Grid> 
      <TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"
         Margin = "235,143,0,0" TextWrapping = "Wrap" Text = "Hello World!"
         VerticalAlignment = "Top" Height = "44" Width = "102" /> 
   </Grid> 
 
</Window> 
  • Now, you will see the change on the Design Window as well.
Design Window
When the above code is compiled and executed, you will see the following window.
First WPF application
Congratulations! You have designed and created your first WPF application.

WPF - XAML Overview

One of the first things you will encounter while working with WPF is XAML. XAML stands for Extensible Application Markup Language. It’s a simple and declarative language based on XML.
  • In XAML, it very easy to create, initialize, and set properties of objects with hierarchical relations.
  • It is mainly used for designing GUIs, however it can be used for other purposes as well, e.g., to declare workflow in Workflow Foundation.

Basic Syntax

When you create your new WPF project, you will encounter some of the XAML code by default in MainWindow.xaml as shown below.
<Window x:Class = "Resources.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "525"> 
 
   <Grid> 
         
   </Grid> 
 
</Window>
The above XAML file contains different kinds of information. The following table briefly explains the role of each information.
InformationDescription
<WindowIt is the opening object element or container of the root.
x:Class = "Resources.MainWindow"It is a partial class declaration which connects the markup to the partial class code defined behind.
xmlns ="http://schemas.microsoft.com/win fx/2006/xaml/presentation"Maps the default XAML namespace for WPF client/framework
xmlns:x ="http://schemas.microsoft.com/w infx/2006/xaml"XAML namespace for XAML language which maps it to x: prefix
>End of object element of the root
<Grid>
</Grid>
It is starting and closing tags of an empty grid object.
</Window>Closing the object element
The syntax rules for XAML is almost similar to XML. If you look at an XAML document, then you will notice that it is actually a valid XML file, but an XML file is not necessarily an XAML file. It is because in XML, the value of the attributes must be a string while in XAML, it can be a different object which is known as Property element syntax.
  • The syntax of an Object element starts with a left angle bracket (<) followed by the name of an object, e.g. Button.
  • Define some Properties and attributes of that object element.
  • The Object element must be closed by a forward slash (/) followed immediately by a right angle bracket (>).

Example of simple object with no child element

<Button/> 

Example of object element with some attributes

<Button Content = "Click Me" Height = "30" Width = "60" /> 

Example of an alternate syntax do define properties (Property element syntax)

<Button> 
   <Button.Content>Click Me</Button.Content> 
   <Button.Height>30</Button.Height> 
   <Button.Width>60</Button.Width> 
</Button> 

Example of Object with Child Element: StackPanel contains Textblock as child element

<StackPanel Orientation = "Horizontal"> 
   <TextBlock Text = "Hello"/> 
</StackPanel> 

Why XAML in WPF

XAML is not only the most widely known feature of WPF, but it's also one of the most misunderstood features. If you have exposure to WPF, then you must have heard of XAML; but take a note of the following two less known facts about XAML −
  • WPF doesn't need XAML
  • XAML doesn't need WPF
They are in fact separable pieces of technology. To understand how that can be, let's look at a simple example in which a button is created with some properties in XAML.
<Window x:Class = "WPFXAMLOverview.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "604"> 
 
   <StackPanel> 
      <Button x:Name = "button" Content = "Click Me" HorizontalAlignment = "Left"  
         Margin = "150" VerticalAlignment = "Top" Width = "75" /> 
   </StackPanel> 
 
</Window> 
In case you choose not to use XAML in WPF, then you can achieve the same GUI result with procedural language as well. Let’s have a look at the same example, but this time, we will create a button in C#.
using System.Windows; 
using System.Windows.Controls;  

namespace WPFXAMLOverview { 
   /// <summary> 
      /// Interaction logic for MainWindow.xaml 
   /// </summary> 
 
   public partial class MainWindow : Window { 
 
      public MainWindow() { 
         InitializeComponent(); 
   
         // Create the StackPanel 
         StackPanel stackPanel = new StackPanel(); 
         this.Content = stackPanel; 
   
         // Create the Button 
         Button button = new Button();
         button.Content = "Click Me"; 
         button.HorizontalAlignment = HorizontalAlignment.Left; 
         button.Margin = new Thickness(150); 
         button.VerticalAlignment = VerticalAlignment.Top; 
         button.Width = 75; 
         stackPanel.Children.Add(button);  
      } 
   } 
} 
When you compile and execute either the XAML code or the C# code, you will see the same output as shown below.
XAML Output
From the above example, it is clear that what you can do in XAML to create, initialize, and set properties of objects, the same tasks can also be done using code.
  • XAML is just another simple and easy way to design UI elements.
  • With XAML, it doesn’t mean that what you can do to design UI elements is the only way. You can either declare the objects in XAML or define them using code.
  • XAML is optional, but despite this, it is at the heart of WPF design.
  • The goal of XAML is to enable visual designers to create user interface elements directly.
  • WPF aims to make it possible to control all visual aspects of the user interface from mark-up.

WPF - Elements Tree

There are many technologies where the elements and components are ordered in a tree structure so that the programmers can easily handle the object and change the behavior of an application. Windows Presentation Foundation (WPF) has a comprehensive tree structure in the form of objects. In WPF, there are two ways that a complete object tree is conceptualized −
  • Logical Tree Structure
  • Visual Tree Structure
With the help of these tree structures, you can easily create and identify the relationship between UI elements. Mostly, WPF developers and designers either use procedural language to create an application or design the UI part of the application in XAML keeping in mind the object tree structure.

Logical Tree Structure

In WPF applications, the structure of the UI elements in XAML represents the logical tree structure. In XAML, the basic elements of UI are declared by the developer. The logical tree in WPF defines the following −
  • Dependency properties
  • Static and dynamic resources
  • Binding the elements on its name etc.
Let’s have a look at the following example in which a button and a list box are created.
<Window x:Class = "WPFElementsTree.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "604"> 
 
   <StackPanel> 
      <Button x:Name = "button" Height = "30" Width = "70" Content = "OK" Margin = "20" /> 
  
      <ListBox x:Name = "listBox" Height = "100" Width = "100" Margin = "20"> 
         <ListBoxItem Content = "Item 1" /> 
         <ListBoxItem Content = "Item 2" /> 
         <ListBoxItem Content = "Item 3" /> 
      </ListBox> 
  
   </StackPanel> 
 
</Window> 
If you look at the XAML code, you will observe a tree structure, i.e. the root node is the Window and inside the root node, there is only one child, that is StackPanel. But StackPanel contains two child elements, button and list box. List box has three more child list box items.

Visual Tree Structure

In WPF, the concept of the visual tree describes the structure of visual objects, as represented by the Visual Base Class. It signifies all the UI elements which are rendered to the output screen.
When a programmer wants to create a template for a particular control, he is actually rendering the visual tree of that control. The visual tree is also very useful for those who want to draw lower level controls for performance and optimization reasons.
In WPF applications, visual tree is used for −
  • Rendering the visual objects.
  • Rendering the layouts.
  • The routed events mostly travel along the visual tree, not the logical tree.
To see the visual tree of the above simple application which contains a button and a list box, let’s compile and execute the XAML code and you will see the following window.
Visual Tree Structure
When the application is running, you can see the visual tree of the running application in Live Visual Tree window which shows the complete hierarchy of this application, as shown below.
logical_tree
The visual tree is typically a superset of the logical tree. You can see here that all the logical elements are also present in the visual tree. So these two trees are really just two different views of the same set of objects that make up the UI.
  • The logical tree leaves out a lot of detail enabling you to focus on the core structure of the user interface and to ignore the details of exactly how it has been presented.
  • The logical tree is what you use to create the basic structure of the user interface.
  • The visual tree will be of interest if you're focusing on the presentation. For example, if you wish to customize the appearance of any UI element, you will need to use the visual tree.