WPF Deep DiveAniruddha ChakrabartiSr. Solution Architect“If I have six hours to chop down a tree, I will use four hours to sharpen the axe” – Abraham Lincoln
Key benefits of WPFBroad integrationProvides access to normal 2D graphics, controls, 3D, video, speech and rich document viewing with consistent programming model as well as tight integrationHardware accelerationImproved Visual RenderingRetained mode graphicsVector graphicsResolution independence (Device Independent Graphics)Declarative programming (aka XAML)Rich composition, layout and customizationEasy deploymentIncorporates best of Web and WindowsIntegrate developers and designers
WPF Architecture
WPF Architecture
WPF: Assemblies and NamespacesPrimary Assemblies containing the WPF APIPresentationFrameworkPresentationCoreWindowsBasemilcore (unmanaged)mil: Media Integration LayerNamespacesSystem.WindowsOther child namespaces starting with System.Windows except System.Windows.Forms (Win Forms)System.Windows.ControlsSystem.Windows.DataSystem.Windows.DocumentsSystem.Windows.Media (+ child namespaces)System.Windows.ShapesManagedUnmanaged/Native
WPF Base Class HierarchyWindowsBasePresentationFrameworkPresentationCore
WPF Base Class DetailsSystem.Threading.DispatcherObject:
Provides basic constructs for dealing with concurrency and threading. WPF is based on a messaging system implemented by the dispatcher - works much like familiar Win32 message pump
System.Windows.DependencyObject:
Provides reach Property System (DP + attached property)
System.Windows.Media.Visual:
Provides for building a tree of visual objects. Visual is designed to be extremely lightweight and flexible, so most of the features have no public API exposure.
Visual is really the entry point to the WPF composition system. Visual is the point of connection between these two subsystems, the managed API and the unmanaged milcore.
System.Windows.UIElement:
defines core subsystems including Layout, Input, and Events
System.Windows.FrameworkElement:
Provides Advanced Layout on top of the features provided by UIElement
Provides DataBinding & Styles
System.Windows.Controls.Control:
Provides Templating SupportDifferent type of WPF applicationsStandalone/Desktop Applications
Window class is used to create windows and dialog boxes
Browser Hosted Applications / XAML Browser Applications (XBAP)
Create Page, Page Function
Loose XAML pages (can be opened in IE)XAML (eXtensibleApplication Markup Language)
XAML OverviewSimple general-purpose, XML based declarative programming language for constructing & initializing .NET objects
.NET Framework 3.0 includes
A compiler and run-time parser for XAML,
Plug-in that enables to view standalone WPF-based XAML files (sometimes called loose XAML pages) inside IE.
Can be used independent of WPF (e.g. WF)
XAML Spec defines rules that map .NET namespaces, types, properties, and events into XML namespaces, elements, and attributes.
Declaring an XML element in XAML (known as an object element) is equivalent to instantiating the corresponding .NET object (always via a default constructor).
Setting an attribute on the object element is equivalent to setting a property of the same name (called a property attribute)XAML Example<Windowx:Class="WpfApplication1.Window1"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/ presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"	Title="First XAML Example" Height="300" Width="300">	<StackPanel><Button Height="70"FontFamily="Verdana"FontSize="18">Hello World</Button></StackPanel></Window>namespace WpfApplication1{    public partial class Window1 :	Window{public Window1(){InitializeComponent();}    }}Window1.xaml.csWindow1.xamlButton btn =new Button();btn.Height = 70;btn.FontFamily =new FontFamily("Verdana");btn.FontSize = 18;btn.Content = "Hello World";panel.Children.Add(btn);
Loose XAML files<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Height="50" Width="250" FontSize="16"> Hello from loose XAML page </Button>
XAML Namespace<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:w="clr-namespace:WpfApplication1"XAML Namespace
Default Namespace: declared with xmlns attribute
Xmlns: http://schemas.microsoft.com/winfx/2006/xaml/presentation - maps to .NET namespace System.Windows.Controls.
Mapping defined in PresentationFramework.dll assembly [assembly:XmlnsDefinition (“http://schemas.microsoft.com/winfx/2006/xaml/presentation”,  “System.Windows.Controls”)]
Root object element in a XAML file must specify at least one XML namespace: used to qualify itself & any child elements.
Additional XML namespaces (on the root or on children) can be declared , but each one must be given a distinct prefix to be used on any identifiers from that namespace.
e.g. WPF XAML files typically use a second namespace with the prefix x (denoted by using xmlns:x instead of just xmlns): xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml (XAML Language namespace) – System.Windows.MarkupXML Properties and Attributes<Button>Hello World               <Button.FontSize>16</Button.FontSize></Button><ButtonFontSize="16">Hello World </Button>Attribute SyntaxProperty Element Syntax<Button Width="120">Hello World</Button><Button Width="1.2in">Hello World</Button><Button Width="1.2 IN">Hello World</Button><Button Width="2.8cm">Hello World</Button><Button Width="70pt">Hello World</Button><Button Width="15e-1in">Hello World</Button><Button Width="NaN">Hello World</Button>
XamlReader ClassXamlReader class exposes some functionality of XAML Parser
Defined in namespace System.Windows.Markup
Load & Parse method allows to parse XAML and convert it into initialized objectApplication and Window class
Application classApplication object is responsible for
Managing the lifetime of the application
Tracking the visible windows
Dispensing resources
Managing the global state of the application
Provides Run() method to start an app
Most WPF apps create a subclass of Application
Run() method starts the dispatcher which sends the messages & events.
WPF requires the UI thread to be STA because many components that WPF uses (e.g. Clipboard) require STA
The [STAThread] marker on the entry-point function is required like Win Forms and User32First WPF Appusing System;using System.Windows;namespace ConsoleApplication1{    class Program{[STAThread]static void Main(string[]args){Window mainWin =new Window();mainWin.Title ="First WPF App";Application app =new Application();app.Run(mainWin);  }    }}
Using VS2008 WPF Template
Important Members of ApplicationProperty
Current (static) – refers to current App
MainWindow – points to application’s Main window
Windows – collection of windows of app
StartupUri – Uri of resource to be started if Run is called without parameter
ShutdownMode
Method
Run – starts the app
Shutdown – ends the app
Events
Startup & Exit
Activated & Deactivated
DispatcherUnhandledExceptionWindowWPF Window provides abstraction for Win32 Window
OS does not distinguish between windows with WPF content and normal Win32 content.
Similar to Form in Win Forms
Represented by System.Windows.Window class
Order of Window events1. Constructor is called.2. Window.Initialized event is raised.3. Window.Activated event is raised.134. Window.Loaded event is raised.5. Window.ContentRendered event is raised.6. User interacts with the window.7. Window.Closing event is raised.8. Window.Unloaded event is raised.9. Window.Closed event is raised.
Navigation WindowProvides navigation in Windows app (like navigation from one page to another in web Apps)
Built with three basic concepts –
Navigation Hosts: hosts the content like Browser
Navigable Content: Page
Journal: responsible for tracking the navigation actions<Label>This is page 1</Label><TextBlock><HyperlinkNavigateUri="Page2.xaml">Go to Page2 </Hyperlink></TextBlock>
Controls
ControlsProvides standard set of controls like Button, TextBox, CheckBox, ComboBox, RadioButton etc.
Provides Content property instead of familiar Win32 Text property. Content can be any object, not only string.
Content actually supports both string and UIElement
For other datatypes, it uses the string value returned by ToString().
Most WPF controls ship with several default appearances
Aero (default Windows Vista theme)
Luna (default Windows XP theme)
Royale (Media Center & Tablet PC theme)
Classic (Win 9x theme)
Provides different type of controls
Content Controls
Buttons
Simple Containers
Containers with a Header
Items Controls
Range Controls
Text and Ink ControlsButtonsProvides Content property - derived from ContentControl base classContent property is of type object (not text), so any content is allowed, not only text.Provides rich composition
Simple ContainersLabel – Can be assigned an Access Key, which can be used to set the cursor to the next TextBox.
ToolTip – provides rich tooltip like Office 2007
Frame – Can contain HTML contentContainers with HeaderGroupBox – Groups other controls. Has Header property.
Expander – New control in WPF. Does not exist in Win32/ WinForms.
Contains a button that enables you to expand and collapse the inner content.
By default, the Expander starts out collapsed.Items ControlComboBox
ListBox
ListView
TabControlCustomizing ComboBoxIsEditable=”False” (default)TextSearch.Text property setIsEditable=”True”
Range ControlProgressBarSlider
Text and Ink ControlTextBoxRichTextBoxCan Contain Rich formatted text & imagesPasswordBoxInkCanvas
OtherMenu, MenuItem
ContextMenu
ToolBar
StatusBar
WPF does not provide these control
Grid
CalendarSizing, Positioning and Transform
SizingLayout and size depends on the negotiation between Parent and Child control
Input
Height & Width property (from FrameworkElement)
Avoid Explicit Sizing
use MinHeight, MinWidth, MaxHeight & MaxWidth
Output
ActualHeight, ActualWidth (read only)
DesiredSize, RenderSize (UIElement)

WPF Deep Dive