Anda di halaman 1dari 73

WPF - An Introduction

Adil Ali Asghar

.NET applications over the


years
.NET 1.0 was a fresh start
But so is .NET 3.0 on-wards
What has changed
Almost every thing about .NET is changed
C# is almost a new language
Properties are not the same properties now
Events are not the same events now

Data binding is different altogether


Data access has taken a great leap now

What to expect?
Basic working knowledge of WPF
No prior WPF knowledge required

You should be able to write a basic


WPF application.
Understand WPF terminology and how it
works
Able to start understanding the advance
concepts of WPF

Some background
A typical windows app used to rely on
User32
creating and managing windows, receiving window messages

GDI/GDI+ ( Graphic Device Interface)

DirectX platform
A tricky game platform for windows app
Relied on hardware acceleration close collaboration with
graphic card vendors
Fast. Use whatever I can from the graphics engine to take
advantage of GPU.
DirectX is more efficient because it understands higherlevel ingredients such as textures and gradients that can
be rendered directly by the video card.

Some background

(contd.)

WPF changed it all


No more dependent upon GDI+
Based upon Direct X
Takes advantage of hardware acceleration

One component thats still in the picture


(to a limited extent) is User32.
handling and routing input
application owns which portion of screen
real estate

Some background
Win App rendering style
Individual paint
Real state model

WPF rendering style


Paint in one go

(contd.)

What WPF has to offer?


Hmm, Hardware acceleration.. Fine but what
else.
Web like layout model
Declarative user interface

Rich drawing model


Rick text model
Animation, a first class citizen
Media support
Styles and templates
Commands
Page based App

Resolution Independence
Typical windows app
Will look smaller on high resolution
Will look larger on low resolution

Resolution independence
Calculates how many pixels required to
make an inch.
So one inch of control remains one inch
of control

Resolution Independence
(contd.)
Due to resolution independence it
requires you to think differently.
Vector rather then bitmap
Bitmap such as icons dont scale properly.
Provides rich support for vectors graphics
which has no scaling issues.

Layout panels to use


Specific way of specifying heights and
widths of UI elements.

WPF Class Hierarchy

WPF Class Hierarchy


WPF application is governed
by a dispatcher that
coordinates messages
(which result from keyboard
input, mouse movements,
and framework processes
such as layout). By deriving
from DispatcherObject,
every element in your user
interface can verify whether
code is running on the
correct thread and access
the dispatcher to marshal
code to the user interface
thread.

WPF Class Hierarchy

Responsible for a powerful


property model
1- Change notification
2- Default values
3- Economical storage
4- Dependency property
model

WPF Class Hierarchy

Core drawing engine


link between the managed
WPF libraries and the
milcore.dll (OS use the same
library) that renders your
display.

WPF Class Hierarchy

Responsible for LIFE


1. Layout
2. Input
3. Focus
4. Events

WPF Class Hierarchy

Adds to UI Element
1. Databinding
2. Animation
3. Styles
4. Positioning

WPF Class Hierarchy

Basic shapes classes, such as


Rectangle, Polygon, Ellipse,
Line, and Path, derive from
this class

WPF Class Hierarchy


A control is an element that
can interact with the user. It
obviously includes classes
such as TextBox, Button, and
ListBox.
The Control class adds
additional properties for
setting the font, foreground,
background and template
support

WPF Class Hierarchy


This is the base class for all controls
that have a single piece of content.
This includes everything from the
humble Label to the Window.
This single piece of content can be
anything from an ordinary string to a
layout panel with a combination of
other shapes and controls.

WPF Class Hierarchy

This is the base class for all controls


that show a collection of items, such
as the ListBox and TreeView.

WPF Class Hierarchy

This is the base class for all layout


containers. Elements that can contain
one or more children and arrange
them according to specific layout
rules

Important point to note


In Windows Forms programming, every visual
item in a form is referred to as a control.
In WPF, this isnt the case. Visual items are
called elements, and only some elements are
actually controls
They can receive focus and interact with the user
There are few exceptions though e.g. Panel
defined in the System.Windows.Controls
namespace, even though they dont derive from
System.Windows.Controls.Control and its not
control.

XAML
Extensible Application Markup
Language
A standard based upon xml
Pronounced as zammel

Not part of WPF


Used at many places

WWF
Silverlight
WPF
XPS (Formatted electronic documents)

Need for XAML


Declarative language for declaring
objects
Gives HTML like power

Used in WPF to separate UI from logic


Why its required?

Graphic designers and Programmers


Design collaboration which is fast
BAML (binary xaml)
Embeded as a resource in assembly

XAML Basics
Every element in a XAML document
maps to an instance of a .NET class.
You can set the properties of each
class through attributes.
Setup complex properties via child
elements.

XAML Basics (contd.)


You can use XAML to
Write event handlers
Write data binding expressions
Defining resources
Defining animations
Defining control templates
Pretty much any thing

Properties in XAML
Simple Properties

Complex Properties

Type Converters
A type converter is used to
To bridge the gap between string values
and non string properties, the XAML
parser needs to perform a conversion.
The conversion is performed by type
converter
Any property decorated with
TypeConverter attribute will work
Any class decorated with TypeConverter
then XAML will use that for each
property of that class.

Important point to note


In a traditional Windows Forms application,
every control has a name.
In a WPF application, theres no such
requirement.
You would only like to name a control if you want
to interact with it in code.
If you create a window by dragging and dropping
elements onto the Visual Studio design surface,
each element will be given an automatically
generated name.
If you remove the name tag, it makes no difference

Lets check out XAML


Lets create a sample project in Visual
Studio 2010 and check out few bits
about XAML.
How class is generated
What is InitializeComponent?
XAML properties

Layout
Typical windows application controls
were fixed in place.
Dock and Anchor

WPF replaced coordinate-based


layout with optional flow-based
layout panels
Resolution independent UI

Layout Philosophy
A WPF window can hold only a single element.
In WPF, layout is determined by the container that
you use.
Elements (such as controls) should not be explicitly sized.
You can limit controls to acceptable sizes by setting a maximum
and minimum size.
Fixed size elements dont work for localization and dynamic
content.

Elements do not indicate their position with screen


coordinates
If you need to add whitespace between elements, you use the
Margin property

There can be exceptions to these rules but generally these


rules prevail.

The Layout Process


2 stage process
Measure stage
Container loops through the child elements
and check their preferred sizes

Arrange stage
The container arranges the child elements
as per preferred size.
If element preferred size is not possible, it will be
truncated unless MinimumSize is mentioned.

Layout Containers
Stack Panel
As the name implies it stacks the elements
On top of each other
Orientation Default or Vertical

Side by side
Orientation Horizontal

Properties

HorizontalAlignment
VerticalAlignment
Margin
Minimum Width, Hight
Width, Height

Lets check out the stack panel in reality

Layout Containers (contd.)


Wrap Panel
Lays out controls in the available space
line by line
column at a time.

Dock Panel
Docks control to edges

Top
Bottom
Left
Right

Layout Containers (contd.)


The Grid
Grid of rows and columns
Important properties
Grid.RowDefinition
Grid.ColumnDefinition
Fixed Width
Auto
Percentage

ShowGridLines
Grid.RowSpan
Grid.ColumnSpan

Grid Splitter
Uniform Grid

Layout Containers (contd.)


Canvas
Coordinate based layout container
Properties

Canvas.Left
Canvas.Top
Explicit sizes
Canvas.ZIndex

Dependency Properties
Dependency properties are required
for a range of WPF features.
change notification
Data binding & Triggers

dynamic value resolution.


Economic storage

Dependency property depends


on multiple property providers, each
with its own level of precedence.

Dynamic Resolution
1

Local Value (XAML)

Project Style

Theme Style

Inherited Value from control hierarchy

Local Value from metadata

Expression e.g. data binding or resource

7
8

Animation, if this property is target of animation


Property Validation, property validation method can
still change

Attached Properties
Dependency property
Defined in a class but applied in another
Grid.Row
Grid.Column

Dependency Props
Lets check them out for real
Local value
Style
Style trigger
Inheritance
Local Value

WPF Events
WPF introduced new event model
called Routed Events
These events have more travelling power
Direct Events
Like ordinary events. E.g. Mouse enter

Bubble Up Events
Move up the control hierarchy
E.g. MouseUp

Tunnel Down Events


Move down the control hierarchy
E.g. PreviewMouseUp

Event fire direction

Lets checkout events in


reality
Bubble Up
Tunnel Down
Attach Events
You can attach to events of a specific
type in enclosing type
Lets check it out.

End of
Day 1

Day 1 Recap
WPF
What it does?
Advantages over win forms

XAML
Benefits of XAML?

Events
Types ?
When to use what type?

Dependency Props
Dynamic resolution?
Benefits

Layout
Panels?
When to use what panel?

WPF Commands
Application command management
Command invocation from various points
Central control
Enabling / disabling
Input Gestures

Prebuild commands

ApplicationCommands
NavigationCommands
EditingCommands
ComponentCommands
MediaCommands

Custom commands

Win form command


handling

WPF Command Handling

Command Sources
Can be the controls who implement
ICommandSource interface.
Expose following properties
Command
CommandParameter
CommandTarget

Whenever a command is fired on


command source, it bubbles up to the
command binding.

Command Binding
Each command source will be
disabled until a command binding is
not made.
Command binding tells
What to do when command is invoked?
How to determine if command can be
executed?

One command binding can work with


many command sources.

Lets checkout command binding in


visual studio

WPF Resources
A reusability tool
Any type can be a resource as long as it can be
used with XAML
Represented with a key
Can be applied to a certain type e.g. Buttons

Resource Hierarchy
Application Level
Window Level
Control Level

Loose XAML resources


Resource dictionaries.
Shared among different projects

WPF Resources
Static
Should be loaded before its referenced.
Handler to resource is obtained once
Normally used for
To improve performance gains

Static resources may change and still reflect the change on


UI if they employ change notification. E.g. brushes

Dynamic
Handler to resource is created every time when it is accessed
Normally used for
System resources
When resources change based upon some other parameters such as
user preferences, locale etc
You want to improve first time load time for better load performance.

Lets checkout resources


We will see how to create resources
at
Application level
Window level
Container level
Control level
Special syntax for static resource

Resource dictionaries

Element binding
Extract some information from a
source object and use it to set a
property in a target object.
The target property is always a
dependency property, and its usually in
a WPF element

Uses XAML markup extension


{Binding ElementName=[source]
Path=[property]}

Binding errors are not shown as

Element Binding
Binding Modes
OneWay
TwoWay
OneTime
OneWayToSource
Can be used to set a property which is not
dependency property

Default

Element Binding
Binding Updates
PropertyChanged
As soon as the property is changed the
binding is updated

LostFocus
Explicit
The source is not updated unless you call
the BindingExpression.UpdateSource()
method.

Default

Lets check out Element


Binding
In this code walk through we will
check
Binding modes
Binding one property with multiple
controls
Binding updates

Binding to non Elements


Bind to Source
Binding to a resource
{Binding Source={StaticResource MyFont}}

Bind to Relative Source


Binding to a path in relative hierarchy e.g. self or
parent container
{Binding Path= Title RelativeSource=
{RelativeSource Type=Winow
Mode=FindAncestor}}

Bind to DataContext
Lets check out code in visual studio

Markup Extensions
Attribute starting with { mark the start of an extension
Provides an instance of appropriate object
Convenient specialized syntax

Types
Static Resource
Dynamic Resource
Source
Relative Source
Binding
x:Type
x:Static
x:Null
x:Array

Localization
Lets check out localization features
of WPF application.

Styles
One of the most powerful concepts
Work like CSS
Essentially style is a collection of property
settings

Can be targeted for a certain control type


Can be cascaded
Can be inherited or overrided
Support triggers
Support templates

In a nutshell style is just a most common type


of resource you will use.

Lets check out styles


We will do a code walkthrough
What roles resources play?
What can styles do?
Cascading
Inheritance
Triggers

Control Templates
Change the UI appearance
Implemented via Style
Dependency property Template
Object of type ControlTemplate

Template can be replaced to give new UI


Basic functionality like keyboard and mouse
handling is not disturbed.
So WPF controls are also referred to as lookless controls.

Markup TemplateBinding is used to bind


properties of elements in the visual tree to
properties of the control.

Lets check out Templates


We will do a code walkthrough
Create a basic rounded button
Create a bit more sophisticated rounded
button
A bit more exciting demos

Things to be investigated
Based upon what you have learned so
far you can check the following at your
own.
Different UI controls
Menus
Toolbars
etc.

Shapes, brushes and transforms


Geometrics and Visuals
Animations

What to expect
In the next and last session we will
be
Exploring what is EF
Entity Framework 4.0
Entities
POCO

LINQ (Language Integrated Query)


LINQ to SQL

WPF data controls


Data templates

Animation
Replaced timer based system with
property based system.
It paints pixels, not controls
Animation is segregated from controls

Fixed frame rate


Complex animations
WPF a retained graphics model
Window is automatically redrawn upon
change

Animation is not series of frame


changes
It just changing the value of some
dependency property.

Data binding
Pull information out of an object and
stuff it into another one
DataContext
{Binding. expression
Lets check it out.
We will create a small UI binding to a table in
database.

Data binding
Binding to collection of objects
WPF classes which derive from ItemsControl can
display a list of objects
ListBox, ComboBox, ListView, DataGrid

Three properties
ItemsSource
(collection implementing IEnumerable)

DisplayMemberPath
ItemTemplate
Custom data template to change the way control is rendered.

Data Formatting
StringFormat, Multibinding

Validation

Data Views
Automatically created and sits between your data
source and bound control. (CollectionViewSource)
Tracks current item and supports sorting, filtering and
grouping
Independent of data source, i.e. you can apply two
different filters on different controls against same data
source
View Scenarios
IBindingList data source, a BindingListCollectionView
(ADO.NET DataTable)
IList data source, a ListCollectionView (ObservableCollection)
Ienumerable data source a CollectionView.

List View
Adds to List box functionality
Adds columns to list box
Switch between views without rebinding

Anda mungkin juga menyukai