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.