Saturday 17 November 2012

XAML

XAML stands for Extensible Application Markup Language and pronounced as "zammel”.

XAML is the programming language introduced in .net framework 3.0 to create rich user interface for WPF, Silverlight and Windows Phone applications.

XAML is XML based markup language to instantiate and initialize .net objects

Below diagram provides a simple overview of WPF - XAML

As we can see in above image,

XAML Elements are arranged in hierarchy manner. XAML elements contains other nested elements. This creates Logical Tree of controls in User Interface.

XAML Root Element:

Every XAML document has root/top element. In WPF, Window is the top level element. In Silverlight UserControl is the top level element.

XAML Namespaces:

CLR namespace are imported into XAML using xmlns attribute. Once CLR namespace is imported into XAML, classes of that namespace become available in XAML for use. In WPF, there are 2 standard namespaces that are imported into XAML.

1. http://schemas.microsoft.com/winfx/2006/xaml/presentation is related to core WPF namespace which contains all WPF Classes including WPF Controls that we use to construct User Interface. This namespace is declared without any prefix, marking it as default namespace for the document. Hence we can use all WPF controls in XAML without using any prefix.
2.   http://schemas.microsoft.com/winfx/2006/xaml is XAML namespace that defines the XAML keywords. This namespace is declared using prefix “x”. Hence any class in this namespace can be referred using x:ElementName.

XAML Elements:

Every Element in XAML maps to an instance of .net class.

<Button />

<Button /> syntax creates an instance of Button class using parameterless constructor. XAML relies on parameterless constructors to create an instance of class and hence classes that needs to be used in XAML must provide parameterless constructor. With WPF 4.0, it is also possible to pass arguments to constructors.


XAML Attributes:


Attribute of XAML Element maps to properties of .net class.

<Button Content="Home" Width="150" Height="50" Background="LightBlue">

Attributes like Content, Width, Height and Background maps to Button control properties respectively.


Property Element Syntax:
In above example, we have used inline attributes to set properties of a control. Ex: Content = “Home”. Here we set simple string as value for Content property. But what if we wish to assign a complex object to property. Ex: A Button that has Image and Text as Content. This can be done using Property Element Syntax. Each property can be set using element rather than attributes.

<Button Width="150" Height="60">
<Button.Content>
<StackPanel Orientation="Horizontal">
<Image Source="Home.png" Stretch="None"></Image>
<TextBlock Text="Home" VerticalAlignment="Center" Margin="10" FontSize="14" ></TextBlock>
</StackPanel>
</Button.Content>
</Button>

Output



Another example: Create a linear gradient effect for Background property instead of simple Background = “LightBlue”.

<Button Content="Home" Width="150" Height="50">
<Button.Background>
<LinearGradientBrush StartPoint="1, 0" EndPoint="1, 1">
<GradientStop Color="LightSkyBlue" Offset="0"></GradientStop>
<GradientStop Color="White" Offset="1"></GradientStop>
</LinearGradientBrush>
</Button.Background>
</Button>

Output


 


Implicit Type Converters:


Type Converters as the name suggests would convert value from one type to other and Implicit means that conversion happens in background. WPF has lot of built-in Type Converters. Let’s see below examples to understand where Type Converters are used and how they work.

<Button Content="Home" Width="150" Height="50" Background="LightBlue" Margin="10">

Example: We set Background property of Button control as Background = “LightBlue”. Now if we see Background property declaration in System.Windows.Controls.Control class then we find below.


Quick Tip: Write this.Background in code behind, move the cursor over Background and press F2 or “Go To Definition” which will take you to the property declaration.

public Brush Background { get; set; }

So Background property expects “Brush” object as value and we have assigned simple string to Background property. Here comes Built-In Type Converter that converts “LightBlue” string value to “System.Windows.Media.Brushes.LightBlue”.


Note: “System.Windows.Media.Brushes.LightBlue” is Named brush in WPF which internally returns an instance of SolidColorBrush of Color LightBlue.


Another example: Margin = “10”.


Now if we see Margin property declaration in System.Windows.FrameworkElement class then we find below.

public Thickness Margin { get; set; }

Margin property expects “Thickness” object as value and we assign value as 10. So Built-In type converter converts “10” to something as “new Thickness(10, 10, 10, 10)”.


OK. So how does XAML Parser decide which Type Converter to be used. XAML Parser checks for 2 places to identify Type Converter to be used.



1. Property Declaration: XAML Parser looks at property declaration for TypeConverter attribute. Margin property declaration below does not have have any information of TypeConverter.

public Thickness Margin { get; set; }


2. Class Declaration of related Data Type: If no information found in property declaration, XAML Parser looks at Class Declaration of related Data Type. In case of “Margin” property, data type is Thickness. So let’s check the Thickness class declaration.


[Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)]
[TypeConverter(typeof(ThicknessConverter))]
public struct Thickness : IEquatable<Thickness>
{
// Actual Code. Omitted for simplicity.
}


Here XAML Parser finds TypeConverter attribute with ThicknessConverter as the actual Type Converter to be used.


If no TypeConverter is found and if there is data type mismatch then XAML Parser throws error.


Same way, there are several other built-in converts being used in WPF.


Markup Extensions


Till now we have set hard code values for attributes/properties in XAML. Many times we also need to set property values to an existing object, to some other control properties or set dynamic value. In such scenarios, Markup Extensions are very useful. Markup Extensions are like Placeholders for actual values that are retrieved at run time. Markup Extension are specified between using curly braces { }.



StaticResource Markup Extension example


We have seen an example above where we created linear gradient effect for Background property directly in Button control using Property Element Syntax. We would do that slightly differently.


Add linear gradient effect as an object to resource dictionary

<Window.Resources>        
<LinearGradientBrush x:Key="BlueWhiteGradient" StartPoint="1, 0" EndPoint="1, 1">
<GradientStop Color="LightSkyBlue" Offset="0"></GradientStop>
<GradientStop Color="White" Offset="1"></GradientStop>
</LinearGradientBrush>
</Window.Resources>

Use linear gradient effect object using StaticResource Markup Extension

<Button Content="Home" Width="150" Height="50" Margin="10" Background="{StaticResource ResourceKey=BlueWhiteGradient}"></Button>

So here we used StaticResource Markup Extension to bind Background property of Button control to already defined LinearGradientBrush object.



Binding Markup Extension example


Binding is widely used Markup Extension for Data Binding UI controls to .net object properties. Here is a simple example of binding Text property of TextBox control to Name property of custom employee object.

<TextBox Text="{Binding Path=Name}"></TextBox>

There are several different Markup Extension that are used for different purpose. Refer separate post that discuss all Markup Extension in detail.


Attached Properties


Each control provides their own set of properties. Attached properties are those properties which are not provided by the control itself but they are provided by their parent control and are used by child controls to specify their position and behaviors with respect to parent control.

<Grid>        
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Enter Name:" Margin="10"></TextBlock>
<TextBox Grid.Row="0" Grid.Column="1" Height="30" Margin="5"></TextBox>
</Grid>

In this example, Row and Column property are not provided by TextBlock and TextBox control, but they are provided by Grid control. TextBlock and TextBox control uses Grid.Row and Grid.Column to specify its location in Grid control.


Now after understanding some basics of XAML language, we should be able to co-related advantages of XAML.


Advantages of XAML



  • XAML code is lesser, easier to read and understand
  • XAML allows organizing controls in hierarchy manner
  • XAML provided better separation of concerns by separating User Interface and Application/Business logic. User Interface is created using XAML and programming language like C#, VB.net are used to write code for application functionalities.
  • Visual tools like Microsoft Expression Blend are widely used for creating rich UI applications.  Microsoft Expression Blend generate XAML code which can be directly used in WPF applications.
  • XAML introduced concept of declarative programming with dependency properties and powerful data binding

Tuesday 23 October 2012

Styles in WPF

I would cover WPF Style feature in 2 posts.

1. Style basics

2. Style in Depth

In this post, we look at the basics of style, creating simple style and applying style.

1. Style basics

Styles are used to provide consistent look and feel to the application. Styles are similar to CSS in HTML web pages. Styles also increase code reusability and maintainability in WPF application.

Let’s start by applying some formatting to Button control.

<Button Content="Hello World" Width="150" Height="50" FontSize="14" FontWeight="Bold" Background="LightBlue" Foreground="DarkBlue"></Button>

Output:


 WPF Styles

Now some questions that come to mind when I see above code?


  • What if I want to apply same formatting to other Button controls. I need to copy and paste the code everywhere. At times when we create custom control template there is lot of code involved. This can lead to unnecessary code duplication.
  • What if I want make a mistake in copy paste. This will lead to UI consistency problem.
  • What if I need to change the formatting of Button control. I need to make change everywhere for consistency. What if designer is handling customizations and there are multiple developers in team. There is code maintainability problem.

So, What’s the solution? Simple create a Style for Button control, add all formatting to that style and refer the style in other Button controls. This approach increases code reusability, provides consistent look and feel to application and improves maintainability.


Now that, We have understood the usefulness of Style, let’s jump into creating styles. We create simple style for above Button formatting.


Creating Style

<Window.Resources>
<Style TargetType="Button" x:Key="SimpleButtonStyle">
<Setter Property="Width" Value="150"></Setter>
<Setter Property="Height" Value="50"></Setter>
<Setter Property="FontSize" Value="14"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
<Setter Property="Background" Value="LightBlue"></Setter>
<Setter Property="Foreground" Value="DarkBlue"></Setter>
</Style>
</Window.Resources>

Style class in WPF is used to define style.


TargetType property is set to the type of control for which this style is created. In our case we create style for Button control, so TargetType is set to Button. Note: As TargetType is set to Button, only properties of Button control can be used in style.


x:Key Provides unique key/name to the style we created. This key will be used to refer style in controls.


A style has collection of setters.


Setter: Each setter is used to set value of a single property of control.


And finally, Style is added as a resource to the resources collection of window so that all controls in current Window/Page can refer to the style. Refer Resources post for more details on resources.


Accessing Style in XAML

<Button Name="btnHelloWorld" Content="Hello World" Style="{StaticResource ResourceKey=SimpleButtonStyle}"></Button>

Style property of Button control is set to SimpleButtonStyle (that we created above) using StaticResource markup extension. See Markup Extensions post explains more on different types of markup extensions.


Accessing the style in code programmatically

btnHelloWorld.Style = ((Style)this.Resources["SimpleButtonStyle"]);

Output 


 WPF styles


Applying style to all controls of specific type.


In above case, we have given unique key to Style and refer that key in control. If we remove unique key in Style, then style will be applied to all controls of specified TargetType i.e Button control.


Creating Style

<Window.Resources>
<Style TargetType="Button">
<Setter Property="Width" Value="150"></Setter>
<Setter Property="Height" Value="50"></Setter>
<Setter Property="FontSize" Value="14"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
<Setter Property="Background" Value="LightBlue"></Setter>
<Setter Property="Foreground" Value="DarkBlue"></Setter>
</Style>
</Window.Resources>

Applying Style


No need to set style explicitly. As above style will be applied to all Button controls of current page/window implicitly.

<Button Content="Hello World"></Button>

If we want individual element to opt-out of style, we can explicitly set style of that element to Null.

<Button Content="Hello World" Style="{x:Null}"></Button>

Style in depth


We have seen basic syntax of Style but Style has lot more to offer. We would cover complete syntax of Style in next post “Style in Depth”.

Sunday 30 September 2012

Events in WPF

Events play an important role in handling user interaction in WPF. Event is a message sent  by the control that the program responds to by executing some application code. Each WPF control supports several events that can be handled.

Consider example below.

XAML

<Button Width="100" Height="30" FontSize="14" Content="Click Me" Click="Button_Click"></Button>

Code Behind

private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("You clicked me");
}

In above example, Click is the event that is supported by Button control. Button_Click is the event handler (function) in code behind where I have written code to be executed when button is clicked. When we click on the button, message box will be shown with text “You clicked me”.


Type of Events


Below picture will give a quick overview of type of events in WPF.


WPF Events


1. Direct Events: Direct events have been in existence since windows forms. Direct events are only raised by the control where the event originates.


2. Routed Events: Routed events can be raised by multiple controls in visual tree and can be handled by multiple handlers.


To understand routed event, lets first understand control hierarchy in WPF.


XAML

<Window x:Class="WPFEvents.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>
<ToolBar VerticalAlignment="Top">
<Button Width="100" Height="30" FontSize="14" Content="Click Me" Click="Button_Click"
Background="LightBlue"></Button>
</ToolBar>
</Grid>
</Window>

In above example, controls are arranged in hierarchal manner. Control hierarchy would be Window, Grid, ToolBar and Button. So button click event will be raised by Button, ToolBar, Grid and Window. Note: In above code we have specified click event handler for Button control only. We can also specify click event handler for ToolBar, Grid and Window which is explained in Attached Events section later in this post.


Routed events are of 2 types.


Bubbling Events: Bubbling events follow bottom - up approach and bubble up in the tree. Bubble events are first raised by the original/source control and then raised by the successive parent controls in the tree until the top level element (i.e window element ) is reached. In above case, Button control is the OriginalSource of the event. Hence Click event is first raised by Button control, then it is raised by ToolBar, Grid and Window.


Tunneling Events: Tunneling events follow top - down approach. Tunneling events are first raised by topmost control in the visual tree of original control, then raised by successive child controls until the OriginalSource control is reached. WPF Events with “Preview” keyword prefix to the event name are Tunneling events. Ex: Bubbling event “Click” has “PreviewClick” as tunneling event.


If we look at the function definition of Click event handler, RoutedEventArgs is passed as second argument. This object contains following event arguments.



Handled – Boolean value that Indicates that event is handled or not. Setting e.Handled = True means event is handled and will not be raised by successive controls.



Source - Control that raised the event.



OriginalSource - Source control that raised the event. Normally same as Source except some complex controls.


RoutedEvent - additional event related details.


 


3. Attached Events


So we have understood the concept of RoutedEvents. But in above example, how to specify event handler for parent controls like ToolBar, Grid and Window that does not provide Click event. This can be done Attached Events.


Attached events are the events that control can not define and raise by themselves, but still can provide handler for the events.


XAML

<Window x:Class="WPFEvents.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" ButtonBase.Click="Window_Click">
<Grid ButtonBase.Click="Grid_Click">
<ToolBar VerticalAlignment="Top" ButtonBase.Click="ToolBar_Click">
<Button Width="100" Height="30" FontSize="14" Content="Click Me" Click="Button_Click"
Background="LightBlue"></Button>
</ToolBar>
</Grid>
</Window>

Code Behind

private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("You clicked me");
}

private void ToolBar_Click(object sender, RoutedEventArgs e)
{

}

private void Grid_Click(object sender, RoutedEventArgs e)
{

}

private void Window_Click(object sender, RoutedEventArgs e)
{

}

In above code, ButtonBase.Click is the attached event.


 


4. Application Level Events


Application level events are related to application lifetime and provided by Application object. They are handled in App.xaml and App.xaml.cs. Below are the events that are provided by Application Class.



Activated - Occurs when window is displayed for first time and each time when we switch back from other application to our application window.


Deactivated - Occurs when we switch to other application.


Startup - Occurs when the application is started.


Exit - Occurs when application is closed or shut down.


SessionEnding - Occurs when window session is ending like computer shut down.


DispatcherUnhandledException - When unhandled exception occurs in the application.


Example - App.xaml

<Application x:Class="WPFEvents.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml" Activated="Application_Activated">
<Application.Resources>

</Application.Resources>
</Application>

Code Behind - App.xaml.cs

public partial class App : Application
{

private void Application_Activated(object sender, EventArgs e)
{

}
}

Saturday 29 September 2012

Creating First WPF application

Let’s start by creating our first WPF application

Open Microsoft Visual Studio from Start Menu

Click File –> New project. Select “Windows” in Installed Templates and select “WPF Application” project type.

This will create below WPF project structure.

WPF Project Structure

Understanding Project structure of WPF.

Solution Name - FirstWPFProject. One solution can have multiple projects and class libraries.

Project Name - FirstWPFProject. This is our WPF project that contains project files.

Project Files:

App.xaml - This page is the entry point of the application. When application starts, App.xaml is called first which has reference to the window to be displayed. By default it reference to MainWindow.xaml

App.xaml.cs - This is code behind file for App.xaml page which contains application level events like Startup, Exit, Activated, Deactivated and DispatcherUnhandledException

MainWindow.xaml - This is a sample window added by default and displayed when application starts.

MainWindow.xaml.cs – This is code behind file of MainWindow.xaml to write application logic.

References: .net framework / external assemblies added to this project.

AssemblyInfo.cs - This file contains Information like title, description, product, company, signing and versioning that makes assembly self-describing.

Resources.resx – Resources.resx provide central location to store application resources like strings, images, icons, text files and access them in strongly type manner. Resources.resx files are also used for localization. By default, resources are embedded in project EXE or DLL but can also be complied into separate satellite assemblies.

Settings.settings - Settings are used to store information on user computer. Settings can be user preferences, address of web server, connection strings etc. Application level settings are constant for every instance of application regardless of user. Application level settings are read-only i.e they are defined at design time and their values can not be changed at run time. User settings are user-specific. User settings are read/write i.e they are defined at design time and their values can be read or write at run time.

Thursday 27 September 2012

WPF Development Tools

Microsoft provides 2 main tools for WPF development. Microsoft Visual Studio and Microsoft Expression Blend.

Microsoft Visual Studio

Microsoft Visual Studio is tool used by developers to create WPF UI using XAML language and write application code using CLR compliant languages like C#, VB.net and others. To start with WPF development visual studio would suffice. Visual Studio designer provides basic XAML editing and viewing capabilities but lacks in advanced graphical abilities like styling, gradient effects, templating, animation.

Microsoft provides free education and evaluation version of visual studio called Microsoft Visual Studio Express. You can download it from Microsoft website.

Microsoft Expression Blend

Microsoft Expression Blend is a tool used by designers for creating rich and interactive XAML UI.

Microsoft provides an excellent integration between this tools. Same project can be shared between Visual Studio and Expression Blend. Hence developer and designers can work in collaboration. Designers can create rich UI in Blend and Developers can write complex application logic in Visual Studio.

 

Additional Tools - There are several other free, open source and paid tools available in market that help in better WPF development.

Debugging Tools

WPF Inspector – Excellent and useful tool. WPF Inspector is a utility that attaches to a running WPF application to troubleshoot common problems with layout, databinding or styling. WPF Inspector allows you to explore a live view of the logical- and visual tree, read and edit property values of elements, watch the data context, debug triggers, trace styles and much more

Snoop - Snoop WPF spying utility that allows to inspect Visual Tree of running WPF application and view/change properties, events, datacontext of selected elements in visual tree. Snoop displays list of running WPF applications. When user selects the application, snoop attaches itself to the selected application and displays visual tree of the application. Selecting an element in visual tree will display properties and events of selected element.

Mole - Mole is Visual Studio 2010 debugger visualizer (Plug - in) that makes it easier to debug WPF application. It runs inside Visual Studio 2010 while you are debugging. Mole allows to view

CRACK.NET - Crack.NET is a runtime debugging and scripting tool that gives you access to the internals of a WPF or Windows Forms application running on your computer. Crack.NET allows you to “walk” the managed heap of another .NET application, and inspect all values on all objects/types

WPF Performance Suite (Perforator, Visual Profiler) - Analyze the run-time behavior of your WPF applications and determine performance optimizations.

Productivity Tools

XAML Power Toys - XAML Power Toys can be installed as Visual Studio Plug-In. Power Toys are a set of commands that can be accessed using context menu (right – click) in XAML Editor and generate XAML code automatically for available features.

WPF Toolkit

XAML - There are lot of XAML authoring and viewing tools available on internet.

3D tools - WPF Graphics Tools, ZAM 3D, 3DPaintBrush

Third party WPF Components: Infragistics, Telerik, DevExpress, ComponentOne, Syncfusion, Xceed

SharpDevelop - free alternative to commercial Visual Studio

Other Useful links:

http://www.realsoftwaredevelopment.com/the-complete-list-of-xaml-tools/

http://blogs.msdn.com/b/mswanson/archive/2006/02/26/wpftoolsandcontrols.aspx

Monday 24 September 2012

WPF Architecture

Before we jump into creating our WPF application, it's good idea to understand overall architecture of WPF, major components in WPF architecture and how components interact with each other.

Here is an overall architecture diagram of WPF.

As we can see in above diagram that WPF architecture is a layered architecture having Managed, Unmanaged and core operating system layers. Managed components are exposed as public API and Unmanaged components provides low level functionality of rendering WPF application.

3 major components in WPF architecture are as below.

PresentationFamework

PresentationFamework is a managed component. PresentationFamework sits on the top of architecture framework and is the primary API for creating WPF applications. PresentationFamework provides functionality that we need to build the WPF applications such as controls, data bindings, styling, shapes, media, documents, annotations, animation and more. When we create any WPF project, PresentationFamework.dll is added as reference by default.

PresentationCore

PresentationCore is a managed wrapper around Media Integration Layer and provides public interface for MIL. PresentationCore is the home for WPF Visual System and provides classes for creating application visual tree. The Visual System creates visual tree which contains applications Visual Elements and rendering instructions. Visual System does not render UI but passes rendering instruction, one element at a time to Composition System of MilCore through 2 way Message Transport. When we create any WPF project, PresentationCore.dll is added as reference by default.

MilCore

MIL in MilCore stands for Media Integration Layer. MilCore provides low level rendering functionality for WPF application. MilCore is written in Unmanaged code in order to enable tight integration with DirectX. DirectX engine is underlying technology used in WPF to display all graphics, allowing for efficient hardware and software rendering. MIL has Composition System that receives rendering instructions from Visual System and translates into data that can be understood by DirectX to render user interface.

I hope this article was useful to understand overall WPF architecture.

Saturday 11 August 2012

WPF Overview and Features

WPF (Windows Presentation Foundation) is next generation Microsoft Platform for creating Rich client/desktop application. WPF was first introduced in .net  framework 3.0

WPF is successor to Windows Forms for creating desktop applications. However WPF has introduced major features compared to windows forms.

Below diagram shows WPF features in a nutshell.

WPF Features

In this article we will look at below 3 features of WPF while remaining ones will have their detailed posts.

1.  New Graphics System
Windows forms relied on 2 Windows components for rendering graphical user interface.
User32: Provides looks and feel similar to windows elements (buttons, textbox etc..).
GDI/GDI+: Provides drawing support for rendering shapes, images etc. but involved additional complexity.

These components has their own limitations.
Consider an example of creating a round glossy button or a button with gradient effect. Creating such button be require lot painting and would be hard to create.

WPF and DirectX
WPF does not rely on Windows API for rendering controls. Instead, WPF uses DirectX as underlying technology for rendering graphics. DirectX technology that has been used so far for developing gaming application with 3D graphics will now be used for developed business application using WPF. Hence is possible to create a rich client application that has 2D and 3D graphics.

Moreover each WPF control is rendered using borders, stokes, background fill, text etc. Hence WPF provides better control over what is renders and provides more flexibility of customization.

Hardware Acceleration
DirectX redirects the task of rendering graphics to Graphics Processing Unit, a dedicated processor in Video Card. Thereby CPU can be utilized for other tasks and application can take benefit of graphics capabilities of latest video card.

Comparison of graphical display system in both technologies

Winforms WPF graphcis comparision

2. Separation of Concerns
WPF provides clear separation between user interface design and application logic. User interface is designed using XAML, an separate XML based programming language. XAML can be created in Visual Studio or Expression Blend, an excellent tool for creating XAML based UI. Expression Blend is tool which is used by designers to create stunning WPF UI. Visual Studio is used by developers to write application logic using any CLR complaint languages like C#, VB.net etc. Moreover Expression Blend and Visual Studio can share same project. Hence designer and developed can work independently but in an integrated fashion.

Below is the screenshot of how UI code and application logic were tightly integrated in windows forms. Adding any control on the form or attaching an control event would create automatically generated C# code in code behind file. Hence there was a tight coupling between Form Designer and Code behind. Moreover primary tool for creating UI in windows forms UI was Visual Studio.

Winforms UI and application logic tight coupling

Whereas WPF provides as clear separation of XAML code and application logic as shown in below figure.

WPF Clear Seperation of Concerns

In above screen, Same project is opened in Visual Studio and Expression Blend. Initially, UI (XAML) and application logic are created using Visual Studio. Then after, XAML is modified in Expression Blend to apply linear gradient effect to button which can be done graphically and more easily in Expression Blend. This way designers and developers can work independently and can use the power of different tools to create rich application.

MVVM (Model, View, ViewModel) design pattern when used with WPF enables creating application with better separation of concerns and test driven development.

3. Resolution Independence
When we think of resolution independence, natural thought that comes to our mind is viewing an application under different resolution. WPF resolution independence has somewhat different perspective. WPF resolution independence means that an application when viewed in monitors with different size (12, 14, 15, 17, 20 inch monitor) and different pixel densities / dpi (dots/pixel per inch) should be displayed in same size (in inches).
Let’s first understand the concept of pixel densities and problem associated with that.

Pixel Densities
Pixel Densities is measured as number of pixel/dots per inch. Pixel Densities is knows as PPI or DPI. Pixel densities are calculated using screen resolution and monitor physical size. Higher the pixel density, better is the clarity.

Pixel Densities calculation for Laptop LCD Monitor
Resolution (in pixel): 1366 * 768 (width * height)
Screen Size (in inch):  15.5 inch diagonal. (13.5 inch width * 7.6 inch height).
Diagonal resolution: square root of [ (width x width) + (height x height) ]
                                  : square root of  [ (1366 * 1366) + (768 * 768) ]
                                  : 2455780 pixel
Pixel Density: 2455780/15.5 = 101.1 pixel per inch.
Nowadays we can find monitors, tablets and Smartphone's that have higher pixel densities of 120 dpi, 144 dpi, 200, 300 or even 400 dpi. In future we can expect LCD monitor upgraded with higher resolution and higher pixel densities. iPad2 and iPad3 are same size 9 inch. But iPad3 has 2048 * 1536 retina display resolution and iPad2 has 1024 * 768 resolution. Hence iPad3 has almost double pixel density than iPad2.

Problem
Let’s take an example of traditional pixel based application with 600 pixel width.
Laptop LCD Monitor with Pixel Density of 101 dpi would display this application in approx. 6 Inch (600/101) physical size/area.
But Advanced LCD or tablet with Pixel Density of 200 dpi would display this application in approx. 3 Inch (600/200) physical size. Hence application would be displayed smaller than original designed. We would expect that application would retain the size and take advantage of higher pixel densities to display sharper and better application.

Solution
WPF solved this problem by introducing new concept called device independent units. WPF controls size is specified using device independent units instead of pixel.
1 physical unit = 1 device independent unit * standard system dpi = 1/96 inch * 96 dpi = 1 pixel

Now we consider WPF application that is 600 device independent units in width.
Above mentioned Laptop LCD Monitor
Pixel Density: 101 pixel per inch.
Application size in device independent units: 600
Application size in pixel: 600 * (1/96 * 101) = 631.25 = 632
Application size in inch: 632/101 = 6.25 inch

Advanced LCD or tablet
Pixel Density: 200 pixel per inch.
Application size in device independent units: 600
Application size in pixel: 600 * (1/96 * 200) = 1250
Application size in inch: 1250/200 = 6.25 inch

As we can see from the calculation that In both LCD, physical application size remains same. Hence application would be displayed using same physical size even thought pixel densities are different. Hence application would look similar in both LCD. Only difference would be that application displayed in Advanced LCD or tablet would be sharper and better than normal LCD monitor.

I hope this post would give you a good start in understanding WPF. Keep watching this space for more such posts on WPF.