Advanced Language Concepts in C#
Extra Session
Last Update: 3/09
David Figge
[email protected]
Page 1
Copyright (C) 2009 by David Figge. All Rights Reserved.
WPF,
Delegates and Events,
and Design Patterns
Advanced Language Concepts in C#
Last Update: 3/09
Page 2
Copyright (C) 2009 by David Figge. All Rights Reserved.
Introduction


When Windows Vista was
introduced, it included a
new graphical subsystem,
code named Avalon
It’s purpose was to

Provide a new state-ofthe-art graphics API



Supported through the DirectX module, which
provides low-level graphics APIs for games, etc
Designed to use hardware acceleration at a
low level (when present)
Windows 7 inherited this subsystem, too.
Last Update: 2/11
Page 3
Copyright (C) 2011 by David Figge. All Rights Reserved.
What Is Windows Presentation Foundation?


Windows Presentation Foundation (WPF)
is the .Net component designed to
leverage these new graphical capabilities.
WPF is a graphical subsystem within .Net


Introduced in .Net 3.0
WPF was designed to provide a single
interface to support the flexibility and
needs of today’s modern applications.

It works on Vista/Win7 and XP


Last Update: 2/11
Vista/Win 7 has it automatically
XP requires an update to have .Net 3.0 (minimum)
Page 4
Copyright (C) 2011 by David Figge. All Rights Reserved.
WPF Provides Unified Support for…
Standard
Windows
Support
for 2D
and
elements
(dialog
3D
graphics,
boxes,putting
controls)
including
2D graphics on a
3D surface
This is a good example
of an application that
can be put together
using the capabilities
of WPF, including…
Last Update: 2/11
Easy support for
higher level
graphics (gradient
fills, etc)
The ability to easily
combine graphics,
animation, video,
and audio
The ability to
defining complex
data representation
at the presentation
level
Page 5
Copyright (C) 2011 by David Figge. All Rights Reserved.
Introduction

WindowsFixed
Forms
Format
(WinForms)
Documents
is wereWPF combines all these
Images
and
graphics
the .Net 1.xtypically
and 2.x solution
displayed
Toto
using
use2D
Video
technologies
and
into oneto get
AndAudio,
if youyou
wanted
werewere
displayed
UI design.
something
It basically
likeprovided
Adobe’s
PDF
delving
presentation
Fileusing
into
thelayer
Media
and allowing
fancy
3D
graphics,
you
WinForms,
sometimes
layout capabilities
Format. This
forallows
standard
arena,
documents
which
improved
is supported
and
haddevelopment
to useby
the DirectX
with assistance
from
Windows
to controls
display on
and
screen
ActiveX
asWindows
they will
integration
Media Player
between
all these
technology
COM
object
technology.
controls.
on a printer.
elements.
So WPF takes several, disjointed APIs
within the OS and put them under one
presentation foundation
Windows
Forms
PDF
Windows
Forms/
GDI+
Windows
Media
Player
Direct3D
(DirectX)
WPF
Graphical interface
(e.g. forms and controls)


On-screen documents


Fixed-format documents



Images


Video and audio


Two-dimensional graphics


Three-dimensional graphics

So let’s see how this is
Questions
far?
integrated
intoso
.Net
Last Update: 2/11
Page 6
Copyright (C) 2011 by David Figge. All Rights Reserved.
.Net Architecture
.Net Applications
One
ofvery
the
At
the
For
Sits
keyWPF
elements
base,
of
course,
developers,
beside
within
.Net these
3.0
thePC
CardSpace
we
have
the
the
.Net
technologies
.Net
introduced
Windows
structure
.Net
provides
sits on
Hardware.
The
Development
providing
the
WorkFlow
Windows
is
the
top
identity
The
of the
OSOS,
significant
Tools
are
afor
UIFoundation
support
CommuniCommon
provides
and
verification
consists
the
factor
here
is
key
element
.Net
Language
supports
cations
of
technologies
ultimate
ain.Net
series
of
that
– this
for
Lets
lookthe
applications
Runtime
Foundation,
taking
(CLR)
run-time
to
applications
interface
.Net,
tying
first
time
–and
the
more
structure,
closely
and
providing
information
providing
justcompile-time
run
between
together
on top
the
of
Windows
at
providing
the
WPF
integrating
support
through
in-time
a
application
everything
elements.
.Net. for
presentation
components.
support
for
these
into
series
server
compiling,
of
level
steps
programs
We’ll
from
come
Web
and
layer
will
make
creation
and
.Net,
the
and
(the
security,
peer-toback
the
Logins
hardware
towork
this
in
use
oftoof
debugging
Operating
peer
flow)
memory
network
to its
ahardware
minute…
Active
.Net
System,
and
management,
completion.
communiDirectory.
accelereration
applications
ultimately
the
and
cations.
a hostby
of
provided
in
many
hardware.
othercards
graphics
languages.
services.
Last Update: 2/11
.Net Dev Tools
.Net
WCF
(Indigo)
CardSpace
(InfoCard)
WF
(WorkFlow)
WPF
(Avalon)
Common Language Runtime
.Net 2.0 Base Class Libraries, ASP.Net 2.0, ADO.Net 2.0, WinForms 2.0
Windows OS
(Windows Vista/7, XP, Server)
PC Hardware
Page 7
Copyright (C) 2011 by David Figge. All Rights Reserved.
WPF Components
.Net Applications
Milcore is the
As
themajor
need
From
the
one
forThe
moreof
component
of
beginning
Presentation
All
The
WPF
direct
WPF graphic
that the
is
Windows,
output
Presentation
Foundation
to
the
written in of
programming
presentation
Video
Core
module
layer
occurs
and
unmanaged
came
about
asystem
window
and
audio
provides
implements
through
Codecs
the
code.
Thisfrom
was
(mostly
its
components
the
DirectX.
are
managed
end
used
The
by
needed
for
game
resided
inuser
the
code
presentation
Milcore,
Media
interface
and
performance
developers),
OS, through
reasons,
into
Integration
features,
aremilcore,
also
DirectX
was
functions
in the
especially
written
including
Layer,
and
developed
as
User32
andinGDI
around
timing
Milcore,
unmanaged
layouts,
is the
aimplements
fast,
direct
modules,
of
animations
component
storyboard
the
code.
link
tocore
core
working
in
audio,
video,
that
animations,
services
ties
WPF
for
level
graphics
conjunction
and
into
and
WPF.
DirectX
data
capabilities
of
with
the
core
production
of
binding.
the
OS and
OS
kernel.
2D and
3D
thegraphics.
hardware.
Last Update: 2/11
.Net Dev Tools
.Net
PresentationFramework
PresentationCore
Common Language Runtime
Milcore
Codecs
Media Integration Layer
OS
User32/GDI
DirectX
Kernel
PC Hardware
WPF Component
Non-WPF .Net
Page 8
OS Component
Still doing okay?
Copyright (C) 2011 by David Figge. All Rights Reserved.
Under the Covers

Let’s take a quick look “under the covers” at
WPF


This will help us understand coding aspects as
well
UI Elements are maintained as a group of
Visual objects


Visual objects are maintained in a Composition
Tree, managed by the MIL
Each element of WPF creates and adds one or
more Composition Nodes to the tree


These nodes contain rendering
instructions
So the entire application’s visuals are
represented as a collection of
Composition Nodes.
Last Update: 2/11
Page 9
Copyright (C) 2011 by David Figge. All Rights Reserved.
UI Rendering

So the MIL maintains the visual tree for each
application


Remember these don’t contain visuals, they
contain instructions used to render the visuals
This allows the MIL to retain the visual tree for
each application, so it becomes responsible for
updating the graphics rather than continually
calling into the application via a ‘Paint’ method


Last Update: 2/11
This also allows the application to update the visuals
incrementally, as individual pieces
change, rather than all at once like
traditional Windows apps
Animations become simple incremental
changes applied based on a timer interval.
Page 10
Copyright (C) 2011 by David Figge. All Rights Reserved.
UI Rendering

So the MIL maintains the visual tree for
each application



The MIL has a dedicated thread that
periodically updates the visuals as changes
occur
The MIL uses a “painters algorithm” that
renders elements from back to front, allowing
you to skip areas that are covered and handle
complex aspects like transparency easily.
The rendering of the UI is also assisted via
the Graphics Processing Unit on the video
adapter (if present)
Last Update: 2/11
Page 11
Copyright (C) 2011 by David Figge. All Rights Reserved.
Managing the UI: Properties


WPF employs a data-driven system for
displaying user content
After the initial rendering, visual
objects are updated via Properties


These properties may represent data
changes (like a new record to display), or
any other visual aspect (like IsVisible)
These properties can be set manually via
code, or bound to an element and
updated automatically
Last Update: 2/11
Page 12
Copyright (C) 2011 by David Figge. All Rights Reserved.
Managing the UI: Properties


So, the visuals are largely customized by a
collection of Properties
These properties, however, also support
an inheritance element



Base level properties (like FontSize) are
inherited by child elements
So, when base properties are changed, child
elements are notified as well
This is also good, because elements may have
dozens (or hundreds) of properties managing
visuals, and this avoids each element
retaining copies
Last Update: 2/11
Page 13
Copyright (C) 2011 by David Figge. All Rights Reserved.
Managing the UI: Properties



Finally, the Property system also supports
“Attached Properties”
An example: A Grid Panel allows
elements to be laid out in a Grid format
(columns and rows)
Each element on the grid has an
‘attached’ property of the grid row and
column

This is only because the grid is ‘holding’ the
element.

Last Update: 2/11
This isn’t inheritance, because on a different
layout, the properties may change
Page 14
Copyright (C) 2011 by David Figge. All Rights Reserved.
Under the Covers

So each application has two threads

One for rendering and repainting


And one for managing the UI



This one generally runs by itself without developer
help
Input from the user, changes you cause
programmatically
This is important, because any processing
you do in your program takes place in the
UI thread, effectively freezing the UI
So any type of lengthy operations
(that might be felt by the UI)
should be done in a
background thread
Last Update: 2/11
Page 15
Copyright (C) 2011 by David Figge. All Rights Reserved.
But Wait, There’s More!

Some additional aspects worth
discussing (and we will over the next
several slides):








Graphical Services
Interoperability
Media Services
Animations
Data Binding
Annotations
Imaging
Documents
Last Update: 2/11
Page 16
Copyright (C) 2011 by David Figge. All Rights Reserved.
Graphical Services

All graphics (including windows) are through
Direct3D, providing


A unified way to displaying from simple (Win32
level) graphics to complex 3D graphics
The ability to offload graphics tasks to the
Graphics card GPU




This can reduce the workload on the computer's CPU.
Use of vector-based graphics, which allow
lossless scaling.
Supports 3D model rendering and
interaction in 2D applications.
Allows interactive 2D content to
be overlaid on 3D surfaces
natively (cool stuff!).
Last Update: 2/11
Page 17
Copyright (C) 2011 by David Figge. All Rights Reserved.
Interoperability

WPF provides interoperability with the
Windows API



Via hosting, one can use Windows
Presentation Foundation inside existing
Win32 code
Or one can use existing Win32 code
inside Windows Presentation Foundation.
Interoperability with Windows Forms
is also possible through the use
of the ElementHost and
WindowsFormsHost classes.
Last Update: 2/11
Page 18
Copyright (C) 2011 by David Figge. All Rights Reserved.
Media Services

WPF provides shape primitives for 2D
graphics




Also provides a built-in set of brushes, pens,
geometries, and transforms.
It also supports 3D UI, 3D documents, and
3D media.
Supports most common image formats.
Supports video formats WMV,
MPEG and some AVI files by default

Because Windows Media Player
is running underneath, WPF can
use all the codecs installed for it.
Last Update: 2/11
Page 19
Copyright (C) 2011 by David Figge. All Rights Reserved.
Animations

Time-based animation. Scene redraws are
time triggered.



Presentation timers are initialized and
managed by WPF.
Scene changes coordinated via
storyboards.



Isn’t affected by CPU speed and load
This makes them easy to code
Animations can be triggered by other
external events, including user action.
Ships with a set of predefined effects,
such as fade out for all controls.
Last Update: 2/11
Page 20
Copyright (C) 2011 by David Figge. All Rights Reserved.
Data binding

WPF supports three types of data binding:





LINQ queries can act as data sources for data
binding.
Binding of data has no bearing on
its presentation.


One time: where the element ignores updates
One way: where the element has read-only
access to data.
Two way: where the element can read from and
write data
WPF provides data templates to
control presentation of data.
Base controls provided by WPF:
buttons, menus, grids, list boxes, etc.
Last Update: 2/11
Page 21
Copyright (C) 2011 by David Figge. All Rights Reserved.
Annotations

Annotations can be applied on a perobject basis via WPFs Document or
FlowDocument element.


WPF only provides the capability for
creating, storing and managing
annotations
Each application must expose the UI on
their own.
Last Update: 2/11
Page 22
Copyright (C) 2011 by David Figge. All Rights Reserved.
Imaging

WPF uses the native Windows Imaging
Component (WIC) code and APIs

This means developers can write image
codecs for their specific image file formats.
Last Update: 2/11
Page 23
Copyright (C) 2011 by David Figge. All Rights Reserved.
Effects

WPF provides for bitmap effects


Although .Net 3.5+ and hardware support
required
Special effects such as drop shadows
and blurring are built in.
Last Update: 2/11
Page 24
Copyright (C) 2011 by David Figge. All Rights Reserved.
Documents

WPF natively supports paginated
documents.


It provides the DocumentReader class,
which is for reading fixed layout
documents.
The FlowDocumentReader class offers
different view modes such as
per-page or scrollable

Last Update: 2/11
It also reflows text if the
viewing area is re sized.
Page 25
Copyright (C) 2011 by David Figge. All Rights Reserved.
UI Separation


So, clearly, WPF is bringing a lot of power
to the UI and code development ‘table’.
Another direction that WPF used was to
separate the design of the UI from the
code to support that UI

This is a method that was introduced with
ASP



UI Design elements are stored in one file
Code to support the UI is stored in a “Code Behind”
page with the same name
Visual Studio handles all the naming and
management details
Last Update: 2/11
Page 26
Copyright (C) 2011 by David Figge. All Rights Reserved.
The Design Page

In WPF, the design elements are defined
in a file with a XAML extension




Rhymes with “Camel”
Stands for eXtended
Application Markup
Language
This is an XML-based
document that has
definitions for all the
UI elements of a window
Each window has its own
xaml page
<Window x:Class="MoreShapes.Window
xmlns="http://schemas.microsoft.co
xmlns:x="http://schemas.microsoft.
Title="Window1" Height="339" Wid
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="24”
<RowDefinition Height="aut
</Grid.RowDefinitions>
<Menu Grid.Row="0">
<MenuItem Header="File">
<MenuItem Header="Exit
</MenuItem>
<MenuItem Header="Shape">
<MenuItem Header="Circ
<MenuItem Header="Squa
<MenuItem Header="Tria
</MenuItem>
<MenuItem Header="Border">
<MenuItem Header=“Red”
<MenuItem Header=“Blue
<MenuItem Header=“Gree
</MenuItem>
Window1.xaml
Last Update: 2/11
Page 27
Copyright (C) 2011 by David Figge. All Rights Reserved.
The Code Behind Page

The Code Behind page contains code
that supports the UI


It’s usually best to keep
this to code just required
to support the
window’s UI
Avoid putting business
logic in this file

This decouples the
business logic from
the UI elements
using System.Windows.Media;
<Window x:Class="MoreShapes.Window
using System.Windows.Media.Imaging;
xmlns="http://schemas.microsoft.co
using System.Windows.Navigation;
xmlns:x="http://schemas.microsoft.
using System.Windows.Shapes;
Title="Window1" Height="339" Wid
<Grid>
namespace MoreShapes
<Grid.RowDefinitions>
{
<RowDefinition Height="24”
/// <summary>
<RowDefinition Height="aut
/// Interaction logic for Window1
</Grid.RowDefinitions>
/// </summary>
<Menu Grid.Row="0">
public enum ShapeTypes { Circle,
<MenuItem Header="File">
public partial class Window1 : Wi
<MenuItem Header="Exit
{
</MenuItem>
ShapeTypes currentShape = Sha
<MenuItem Header="Shape">
bool dragging = false;
<MenuItem Header="Circ
Rectangle rubberBand = null;
<MenuItem Header="Squa
Point rubberBandStart = new P
<MenuItem Header="Tria
Shape draggingShape = null;
</MenuItem>
Point dragOffset = new Point(
<MenuItem Header="Border">
Brush[] TheColors = { Brushes
<MenuItem Header=“Red”
Brush currentBorder;
<MenuItem Header=“Blue
Brush currentFill;
<MenuItem Header=“Gree
Shape selectedShape = null;
</MenuItem>
Window1.xaml.cs
Last Update: 2/11
Page 28
Copyright (C) 2011 by David Figge. All Rights Reserved.
Why This Separation?

The purpose behind this separation is to
allow the UI design and the support code
to be done as separate processes



UI design is a specific skill from programming
And, typically, programmers are not good UI
designers
So this separation really
allows UI designers and
programmers to have the
ability to work together,
but not work in the same files
Last Update: 2/11
Page 29
Copyright (C) 2011 by David Figge. All Rights Reserved.
Let’s Give it a Try!


At its simplest level, WPF can be very
easy to work with
Visual Studio provides an easy form
design mode that allows for simple
drag-and-drop functionality


You don’t need to work with the Xaml
code until you want something more
advanced
In this example, we’ll have a label, a
text box, a button, and a message box

We’ll do this together as a class…
Last Update: 2/11
Page 30
Copyright (C) 2011 by David Figge. All Rights Reserved.
Our First WPF App


Create a new WPF Windows app called Birthday
Drag the controls from the Toolbox and drop them onto the
form as shown



Use the Properties window to set
 The Content of the label
to “Your name:”
 The Content of the button
to “Today’s My Birthday!”
Double-click on the button to
go to it’s handler in the
code-behind page. Code:


Note how the xaml code
changes as you add the controls
Textbox
Label
Your Name:
Today’s My Birthday!
Button
MessageBox.Show(“Happy Birthday, “ + textBox1.Text + “!”);
Give it a try!
Last Update: 2/11
Page 31
Copyright (C) 2011 by David Figge. All Rights Reserved.
Let’s See What We’ve Got…


Let’s take a look at some of the
elements that make up this program
First, looking at the code page
(Window1.xaml.cs)…
Last Update: 2/11
Page 32
Copyright (C) 2011 by David Figge. All Rights Reserved.
Window1.xaml.cs
Note the keyword partial.The first thing we see is the
This means that there’s
definition ofInthe
thisWindow1
case, theclass.
rest of
class definition
This is derivedthe
from
theis C#
usingmore
System;
class
in aWindow
system
somewhere
else
in
the
...
class, which
encapsulates
the
generated
at each
build
project.
namespace Birthday
functionality
ofthe
a Window
from
xaml code
{
}
/// ...
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Happy
Birthday
" + system
textBox1.Text
"!");
The primary element
in that
generated+ file
is
}
the InitializeComponent function. The purpose of
}
this function is to create the window based on the
Last Update: 2/11
instructions in the xaml code. So, although we can’t
edit this function directly, we control what’s in that
function by modifying the xaml code. Let’s take a
look at the xaml code…
Page 33
Copyright (C) 2011 by David Figge. All Rights Reserved.
Window1.xaml
Inside the Window, we have a
Grid element. A grid is one of
several layout elements, which
<Window x:Class="Birthday.Window1"
are responsible for positioning
and supporting other elements
xmlns="http://schemas.microsoft.com/...
(like
controls).
Inside
the
Grid
As we discussed,
xaml
is specific
style
of
xmlns:x="http://schemas.microsoft.com/...
This
defines
the
class
that’s
tags
we
find…
xml. Our root element
is the Window
Title="Window1"
Height="247"
associated
with theWidth="311">
window
tag, stating that this
xaml
code
(the Window1 class in the
<Grid>
describes a window (there
are other
Birthday
...options, which we’ll get to) namespace)
Still in the Window tag, we’re
setting some properties of the
Window – its title and size. We
</Grid>
can add more if we need to.
</Window>
And here’s the closing tag
of the root element
Window.
Last Update: 2/11
Page 34
Copyright (C) 2011 by David Figge. All Rights Reserved.
Window1.xaml
… the controls for our app. So the
grid “owns” the label, textbox,
<Window x:Class="Birthday.Window1"
and button. And the grid, in turn,
xmlns="http://schemas.microsoft.com/...
is “owned” by the window itself.
xmlns:x="http://schemas.microsoft.com/...
Title="Window1" Height="247" Width="311">
<Grid>
<Label ...>Your Name:</Label>
<TextBox ... />
<Button ...>Today's My Birthday</Button>
</Grid>
</Window>
Last Update: 2/11
Page 35
Copyright (C) 2011 by David Figge. All Rights Reserved.
The Layered Approach

This layered approach is important, and generally
reflects the way that a Window is created




A Window consists of a 4 buttons (System, Minimize,
Maximize, and Close button) on top of a Title window,
all on top of that base window.
Windows are
ultimately composites
of many windows
layered on top of one
another.
So the xml-based xaml layout
actually represents this layered window approach
well
So, as you work your way through the xaml code,
you create a visual tree representing the visual
elements of the window.
Last Update: 2/11
Page 36
Copyright (C) 2011 by David Figge. All Rights Reserved.
The Event Handler

Before we leave our Birthday program, let’s go
take a look at our Click handler.
...
<Button ... Name="button1" Click="button1_Click">...</Button>
...

The handler is tied to the button by associating it
with the Click event of the button (in the xaml
code).



Double-clicking on the element creates a handler for
the ‘default’ event. In the case of the button, this is
the Click event
You can also add other handlers by specifying the
association in the xaml code (we’ll do that later).
Note the Name element that gives a unique identifier
to this button, and is used in the default handler’s
name
Last Update: 2/11
Page 37
Copyright (C) 2011 by David Figge. All Rights Reserved.
The Event Handler

Now let’s look at the actual event handler
code…
...
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Happy Birthday " + textBox1.Text + "!");
}
...

All UI event handlers in WPF have two
parameters

Sender, which refers to the triggering element



Last Update: 2/11
In this case, it would be the button
Note that it’s passed as an Object, which means
anything can be passed in the first parameter
If you need use sender to access the button, you’ll need
to cast it to a Button object
Page 38
Copyright (C) 2011 by David Figge. All Rights Reserved.
The Event Handler

Now let’s look at the actual event handler
code…
...
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Happy Birthday " + textBox1.Text + "!");
}
...

The other parameter is a type of EventArgs


Derived from the base class EventArgs
Has information that might be of use to the
handler


For example, MouseEventArgs, passed to MouseMove
events, has the current mouse coordinates
In this case, there’s little useful information to the
button click in RoutedEventArgs
Last Update: 2/11
Page 39
Copyright (C) 2011 by David Figge. All Rights Reserved.
More WPF Basics

As you can see as we just scratch the
surface, there are many aspects to WPF

There are too many to jump into
immediately, but let’s hit some of the
basics before we move on…
Last Update: 2/11
Page 40
Copyright (C) 2011 by David Figge. All Rights Reserved.
WPF Panels


In the Birthday program, we used the
Grid panel
WPF provides several different panels
to suit various needs:
Panel
Use
Grid
Allows absolute placement
Canvas
User defined contents
DockPanel
Allows docking of panels (Left,Top,Right,Bottom)
StackPanel
Stacks elements (vertical or horizontally)
UniformGrid
Places elements into uniform sized columns, rows
WrapPanel
Automatically wraps elements as space fills up
Last Update: 2/11
Page 41
Copyright (C) 2011 by David Figge. All Rights Reserved.
Primary Controls


WPF provides standard controls, as well as
some more complex controls…
Category
Elements
Std Window
Controls
Label, Textbox, Listbox, Combobox, Button, Checkbox,
GroupBox, RadioButton, Scrollbar
Complex Controls
ListView, Border, Canvas, Image, ProgressBar, Tab,
TreeView, Slider, Rich Edit Box, Toolbar. Statusbar
Basic shapes
Ellipse, Rectangle
Sub-Containers
ScrollView, DocumentViewer
Alright. Enough talk. Let’s take a look at a
Calculator program I’ve got written in WPF…
Last Update: 2/11
Page 42
Copyright (C) 2011 by David Figge. All Rights Reserved.
Calculator Program

Let’s talk about…

This basic calculator was made similar to
how one would make it in WinForms


Drag and drop controls, etc.
Adding Styles

A style allows you to control the way controls
look and operate directly from the xaml



Uncomment the style…
Keep storyboard and it’s reference commented out
WPF also allows you to specify animations

Either through code or from the xaml itself

Last Update: 3/09
Uncomment the storyboard and its reference
Page 43
Copyright (C) 2009 by David Figge. All Rights Reserved.
WPF Summary

So what you saw just scratched the
surface, but as you can see WPF gives






Ability to customize control look and feel
(much more than WinForms)
Ability to add 3D graphics, multimedia ,etc
Ability to add animations easily
Inclusion of images, manipulations
Built-in support for documents (pdf…)
Questions on our brief introduction?
Last Update: 3/09
Page 44
Copyright (C) 2009 by David Figge. All Rights Reserved.
Delegates and Events
Advanced Language Concepts in C#
Last Update: 4/11
Page 45
Copyright (C) 2010 by David Figge. All Rights Reserved.
Delegates


Delegates are a software mechanism
to allow function call choices to be
made at runtime.
A reasonable analogy can be drawn
from politics...
Last Update: 4/11
Page 46
Copyright (C) 2010 by David Figge. All Rights Reserved.
Delegates


The President is generally a pretty busy man.
Often when something unexpected arises, such as the death
of a head of state, the President is unable to attend, and must
send his representative





The Vice President, Secretary of State, 1st Lady...
This person is a delegate, and represents our country for that
event
The President defines in advance what responsibility will be
delegated (i.e. attend the funeral), and what parameters
will be passed (i.e. condolences, kind words)
He then assigns a specific person to act
as that delegate at “runtime”, or as the
situation occurs.
In the same way that the President defines
and assigns a delegate “at runtime”, C#
delegates are used to make function call
decisions at runtime.
Last Update: 4/11
Page 47
Copyright (C) 2010 by David Figge. All Rights Reserved.
Delegates




So delegates are used in situations where you need to execute
a particular action, but you don’t know in advance what
method (or maybe even which object) you’ll use to call upon to
execute it.
A delegate is a variable that points to a specific kind of
function in your code.
•
For example, int function(double, double)
•
This is very similar to a function pointer in C/C++
Delegates have many uses, but could probably be generalized
into a couple of categories
 Predefining a function to call
 Callback Functions
Let’s talk about both of these a bit...
Last Update: 4/11
Page 48
Copyright (C) 2010 by David Figge. All Rights Reserved.
Predefining a Function to Call



Sometimes you need to selection what function to call before
you’re actually ready to call the function
For example, perhaps a program
customizable
Sometime has
duringathe
running of the toolbar,
program,
user (function)
selects a buttonto call when
allowing the user to choose
whatthetool
and assigns it to the “Print”
the button is pressed
functionality. They
Whenaren’t
the user
printing,
finallyjust
presses
Let’s diagram
an
By storing
the “function
todefining
call” in
delegate,
you
can call it on
theabutton
the
Print
to print
button,
when
we simply
example along a
pushed.
execute the
the
demand
without
switch
or delegate
if/thenand
statements
At thateasily
point, the
button fora complex
timeline...
the delegate is assigned to
the PrintDocument
function.
PrintDocument function is
Meanwhile, the user
called.
continues to work with
the document.
User wants button
to be “Print”
User presses
button
Delegate = PrintDocument( )
Delegate executes PrintDocument
Does that make sense?
Last Update: 4/11
Page 49
Copyright (C) 2010 by David Figge. All Rights Reserved.
Callbacks Functions



A Callback is a term for a parameter to a
function that is the address of another
function.
For an example, let’s consider a sort function
Sort functions have a challenge



You can make the function be very specific, and
sort integers and floats (and such), but that limits
its usefulness
You can make the function be very general (like
sorting user-defined arrays or arrays of objects),
but you don’t have enough information about
the objects to compare them
This is where the Callback function enters
Last Update: 4/11
Page 50
Copyright (C) 2010 by David Figge. All Rights Reserved.
Callback Functions



By including, as a parameter to Sort, the
function it should use to compare items
(and therefore put them in order), you
can support any type of
data
the
So it calls
into your
code user
(using
the function you provided via
wants
tofunction
sort
So as the system
During
is its processing, the the delegate parameter), and
When
sort is done, your
sorting, it needs to know
sort code So
may
call
intothe
your
your
program
is humming
and
ititems,
your
codeoncompares
the
Ofalong,
course,
your
main
So
usecompare
term
“Callback”
because
program
continues
whichwe
of two objects
isthe routine
many
decides to call the
System’s
Sort
method.
You
returningunaware
the
result execution
to the sortis halted
program
normally,
probably
‘greater’.
times.
the generic sort
code
“calls
back”
into
provide
a callback
function (setting
thethe
delegate
waiting
for
sort to be
of the callsfunction.
to the compare
parameter) of a function that
will
do
the
finished.
your custom code
to perform
its task.
routine.
comparison of two objects.
Let’s diagram this one, too...
System Code
User Code
Have I lost anyone?
Last Update: 4/11
Page 51
Copyright (C) 2010 by David Figge. All Rights Reserved.
Callback Functions




So Callback functions are used to add runtime-based flexibility to
otherwise pretty limited functions

In these cases, the delegate is a parameter in the function (e.g.
sort)
These types of callbacks may be used synchronously (like our sort
example, simply waiting until it’s done before continuing the main
thread...
Or asynchronously. where the called function starts a separate thread
at the start, then returning immediately.

In these cases, there may also be a callback to signify that the
thread has completed

A good example of asynchronous processing is connecting to an
Internet site – you don’t want to hold up the main program until
this is complete. You can simply call a Callback function when
you’re done, which signals the main program of the status.
So we’ve talked a lot about delegates, let’s look at an example...
Last Update: 4/11
Page 52
Copyright (C) 2010 by David Figge. All Rights Reserved.
Delegate Example
This is how we define a delegate. It
is of type delegate, and the
The next step is to define a variable to ‘hold’
delegate is a void function with no
delegate void GradeDelegate();
the function, a variable of type
parameters.
class Student
GradeDelegate. We’ve called this variable
{
Grade,
In A");
this case
– each student will
public void A() { Console.WriteLine(name
+ "and
got–an
}
public void B() { Console.WriteLine(name
got a B"); } that we’ll execute to
have+a "GradeDelegate
public void C() { Console.WriteLine(name + " got a C"); }
find out what grade they got.
public GradeDelegate Grade;
public string name;
Here
public Student(string n) { name = n; };
I declare an array of
the syntax
}
Students,This
and isinitialize
the for
class TestClass {
initializing
a delegate.
These are
functionsYou
we’ll use
first
one
to
“Bob”.
static void Main()
simply
assign
it theThey
namehave
of to
in the
delegate.
{
Now,
Ithe
canyou
print
outsignature
Student[] stds = new Student[1];
thematch
function
want
to use
delegate
stds[0] = new Student(“Bob”);
whatever
gradewith
associated
(include
the object
ifisit’s
(void
functions
noan
stds[0].Grade = stds[0].B;
with the
student
the same
instance
method)
parameters,
in thisbycase).
foreach (Student s in stds)
function call for each Student
s.Grade();
object.
}
}
How are we doing?
Last Update: 4/11
Page 53
Copyright (C) 2010 by David Figge. All Rights Reserved.
Delegate Exercise

I’m going to go back to that WPF Calculator
program we used earlier.


As it is now, when you press the +, -, *, or / key, the
program remembers the operation that you select.



As you use the calculator, you will enter the first
operand, an operator (+,-,*,/), and then the second
operand (like 3 * 4). You then press the = key to get the
total.
We’re going to modify this to use a delegate to hold the
desired operation (Add, Subtract, Multiply, or Divide)
until the = key is pressed.
When it is, we’ll simply call the delegate, passing in the
two operands.
Ready?
Last Update: 4/11
Page 54
Copyright (C) 2010 by David Figge. All Rights Reserved.
Multiple Delegations



One of the great features of delegates is that you can use +=
with them
 So multiple functions can be associated with the delegate
 When the delegate function is called, each function
associated with it will be called in turn
 You can also remove an associated function with -=
Delegates that use this feature are called Multicast delegates
 All delegates are capable of being multicast
Let’s see an example with our Student class we used a while
ago…
Last Update: 4/11
Page 55
Copyright (C) 2010 by David Figge. All Rights Reserved.
Multiple Delgations Example
delegate void GradeDelegate();
class Student
{
public void A() { Console.WriteLine(name + " got an A"); }
public void B() { Console.WriteLine(name + " got a B"); }
public void C() { Console.WriteLine(name + " got a C"); }
static public GradeDelegate Grade;
public string name;
public Student(string n) { name = n; }
}
class TestClass {
static void Main()
{
Student[] stds = new Student[2];
stds[0] = new Student("Bob");
Student.Grade += new GradeDelegate(stds[0].B);
stds[1] = new Student("Mary");
Student.Grade += new GradeDelegate(stds[1].A);
We now create 2 students. Note
that I use += for adding the
Things
have
changed
just a little.
student
to the
Grade
delegate.
First, the Grade variable is now
static (shared for all Student
objects). This makes more sense
with the += syntax.
Student.Grade();
}
}
Now, I simply call
Student.Grade() and it displays
both students’ grade functions:
“Bob got a B”
“Mary got an A”
Pretty slick, huh? Any questions?
Last Update: 4/11
Page 56
Copyright (C) 2010 by David Figge. All Rights Reserved.
Events



So we’ve talked about delegates, now
let’s hit the closely-related subject of
events.
Events are an implementation of the
Publisher/Subscriber design pattern (if
that means anything to you).
The concept behind events is that there
are two pieces:



a publisher (someone with information to
share), and
a subscriber (someone interested in that
information).
Let’s take a look at an example to see if
that clarifies things somewhat...
Last Update: 4/11
Page 57
Copyright (C) 2010 by David Figge. All Rights Reserved.
Publishers and Subscribers





Let’s consider the situation where we have a stock
broker, “Stock Broker Bill”. Stock Broker Bill has
information his clients want– his buy/sell
recommendations for stocks. Stock Broker Bill is
the publisher of this information
Some of Stock Broker Bill’s clients are interested in
getting up-to-the-minute recommendations from
him. The clients are the subscribers
So Bill sets up an event: StockNotify. He uses this
to send his buy/sell recommendations to his
clients.
Any client that is interested can register with the
StockNotify event, and receive the buy/sell
notifications.
Let’s see what this might look like...
Last Update: 4/11
Page 58
Copyright (C) 2010 by David Figge. All Rights Reserved.
Event Declaration Example
public class StockBrokerBill { Also in the class is a function that
registers a client with the
public delegate void dNotify(string ticker);
StockNotify event.
public static event dNotify StockNotify;
public static void Register(dNotify fcn)
{
And then the event
Events are based on
StockNotify += fcn;
itself(StockNotify)
At some point, the eventdelegates
will
(which define the
}
be triggered like this format
This class
represents
of the
function).Stock
Here
public static void(announcing
Main(string[]
args)
that Microsoft
Bill.
weBroker
declare
a delegate
{
stock is going up)
dNotify...
...
// At the right time...
StockNotify(“MSFT”);
}
}
Last Update: 4/11
Page 59
Copyright (C) 2010 by David Figge. All Rights Reserved.
So Bob is a client of Stock
Event Subscription
Example
Broker Bill, and wants to be
notified of stock risings. He
has a method called Notify
that displays a message to
buy.
class Bob
{
public void Notify(string ticker)
{
MessageBox.Show(“Bob: Buy “+ticker);
}
public Bob()
{
StockBrokerBill.Register(Notify);
}
}
In the Bob class constructor, we register
the Notify function with
StockBrokerBill.StockNotify (via
Register). When the stock rises, Bob’s
Notify function will be called, saying
“Bob: Buy MSFT”
Last Update: 4/11
Page 60
Copyright (C) 2010 by David Figge. All Rights Reserved.
Events vs. Delegates




So, if the syntax looks very similar to
delegates, there’s a reason
Events, being based on delegates, use the
same registration and calling process
So what’s the difference between Events and
Delegates? Can you just use the delegate
instead of the event?
Well, from a technical standpoint, there’s not
much difference

Events can only be called from the class that
defined them


So there’s a bit of a security benefit
Delegates – as data elements – can’t be part of
an interface, but events can be
Last Update: 4/11
Page 61
Copyright (C) 2010 by David Figge. All Rights Reserved.
Events vs. Delegates


So most of the difference between Events and
Delegates is conceptual, and by convention rather
than language-enforced rules
Delegates are generally used for local (within the
same application) storage of a function


Events are typically for providing outside access to
an internal resource



Like the calculator
Like registering a function on a remote computer to
Stock Broker Bill’s StockNotify
Or where you wish to have a level of separation
between classes in the same program
Event (and Delegate) Caveats:

The calling order is not predictable, and exceptions
could potentially disrupt subsequent calls
Last Update: 4/11
Page 62
Copyright (C) 2010 by David Figge. All Rights Reserved.
Windows Events




C# Events is the mechanism used to support
Windows Events
Windows programming – like other GUI
environments – is different from programming in
a procedural environment (like the DOS command
prompt)
In Windows programming, the system stays in
control of your program – allowing windows to
be selected and manipulated and swapped
between – and the system notifies your program
when you need to get involved
This removes significant burden of Window
management from the application developer’s
job, and gives a consistent look and feel to all of
Windows
Last Update: 4/11
Page 63
Copyright (C) 2010 by David Figge. All Rights Reserved.
Windows Events





A good example of this is our WinCheckbook
program
Windows handles the basic Windows mechanics
– moving a window, resizing, swapping between
applications.
Windows handles displaying of the pull-down
menus, windows, buttons, etc., but when the user
clicks on a button, only your program knows what
to do
So at that point, Windows contacts your program
and tells it “the user clicked on the Export button”.
You can then respond to the message and
execute the export code
In C#, the mechanism that Windows uses to
support this messaging scheme is Events
Last Update: 4/11
Page 64
Copyright (C) 2010 by David Figge. All Rights Reserved.
Windows Events

Windows defines hundreds of events that can occur
during the running of a program





You can be notified when the window is resized, moved,
minimized, maximized, switched to, switched from, clicked
on, etc.
The trick to Windows programming is knowing what
events occur and the order in which they happen
So Windows makes all these events available to you by
creating C# Events that you can register with
If you want to know if a user clicks on a menu item, you
register a function with the Click event of the menu item.
That way, your code is called when the user clicks on the
menu
Let’s take a look at our WinCheckgook program and see
just where that code actually is for that Export button...
Questions on Events?
Last Update: 4/11
Page 65
Copyright (C) 2010 by David Figge. All Rights Reserved.
Design Patterns
Advanced Language Concepts in C#
Copyright (C) 2005 by David Figge. Unauthorized Use
Design Patterns




Design Patterns are a collection of real-world solutions that
have been proven in the industry over time to solve common
problems
Recognize that we’re not talking about a class or object. We’re
talking about repeating patterns of how objects have been
created, organized, and have interacted with each other to
solve common, repeating problems.
These patterns are in use all around us. No one person
invented them. They’re simply common solutions to common
problems.
As these patterns become recognizable to you, you will be
better able to identify key components, and potential issues to
consider when solving these common issues.
Copyright (C) 2005 by
Page 67
Design Patterns



In the mid-90s Erich Gamma, Richard Helm, Ralph Johnson,
and John Vlissides – also known as the “gang of four” (or GoF)
– cataloged the basic patterns industry continued to use and
reinvent. The result is their book Design Patterns (our text).
The patterns they identified are generally considered the
foundations for all other patterns.
The GoF categorized the patterns in 3 groups
 Creational – Having to do with creating objects
 Structural – Having to do with program structure
 Behavioral – Having to do with object interactions
There are too many patterns to look at in depth, but let’s take
an overview look at these categories and look in detail at some
of the more common patterns...
Copyright (C) 2005 by
Page 68
Creational Patterns


Creational design patterns abstract the
object instantiation process. Used
correctly, they help make a system
independent of how its objects are
created, composed, and represented.
Let’s take a look at two common
patterns:


The Abstract Factory, and
The Singleton
Copyright (C) 2005 by
Page 69
The Abstract Factory





The Abstract Factory pattern is when a client – rather than
creating an object itself – delegates that to an intermediary
object.
By doing this, the intermediary takes responsibility for
determining what the best object is given the current state of
the system.
A computer example might be making a call to the OS to return
a scrollbar object. If I’m under Windows, that scrollbar
will look different than if I’m under Mac OS.
By deferring the decision to the operating system, it
was able to create the appropriate one given the
current system
The client then agrees to use the returned object
according to the common public interface for both scrollbars.
Page 70
Copyright (C) 2005 by David Figge. Unauthorized Use
The Abstract Factory




A real life example (although the book
focuses on object oriented software
versions of these patterns, I just wanted
to show that these patterns don’t only
apply to software, but to real life as well):
When you call a travel agent, you are
delegating the creation of your tickets,
hotel, car, etc to them.
The travel agent creates these items for
you and returns them to you after they
have been created.
You then use the tickets with no further
involvement from the travel agent.
Get the idea?
Copyright (C) 2005 by
Page 71
Singleton



A Singleton is a class where only one object of
that type is allowed to exist in the system.
A good example of this is a print queue. If
multiple print queues were sending jobs to the
same printer, jobs would get intermixed and it
would be a mess
Singletons are usually achieved by having a
static creation function (not a constructor)
that a) if no objects exist creates one,
otherwise b) returns the existing one. At that
point, all interaction with that object type
takes place through that single global point of
access.
Copyright (C) 2005 by
Page 72
Structural Patterns


Structural Patterns deal with how
classes and objects are combined to
create larger solutions.
Let’s take a look at four common
patterns:




The Adapter
The Bridge
The Facade
The Proxy
Copyright (C) 2005 by
Page 73
The Adapter





Also known as a wrapper, the adapter’s job is to
translate the interface of the target class into an
interface that the client wants.
It fits in between the client and the target, and simply
translates method calls between the two.
The queue template and the stack template are
simply adapters on top of a vector that provide a
queue and stack based interface to a client.
Adapters are typically derivations of the target class,
but doesn’t have to be.
Another example is the device that lets 3-prong plugs
go into 2-prong electrical outlets (an “adapter”).
Copyright (C) 2005 by
Page 74
The Bridge








Whereas the Abstract Factory isolated clients from the creation of
objects, the Bridge is used to isolate a client completely from the
details of an implementation...to separate “what you would like” from
“how it is done”.

So where the Abstract Factory simply created an object, the
Bridge is used as an intermediary for an entire process
How about an example:
I have a car “hands free” phone system in my car, using ‘Bluetooth’
wireless technology
With this technology, the hands free unit can work with any
bluetooth enabled cell phone that wants to use it
The hands free knows how to ask a bluetooth phone to make a call,
and
The bluetooth phones lets the hands free interact with that phone
call, but isolates it from how the phone makes the call.
This decoupling of the ‘request’ from the ‘service provider’ allows me
to use any bluetooth phone with my hands free.
Let’s try to diagram this just a little...
Copyright (C) 2005 by
Page 75
The Bridge
Client
Interface
Provider
So weSostart
a client,
a provider.
the with
benefit
of theand
Bridge
is that We
also
The
have
interface
anability
interface
calls
to
object,
a provider
which
takes
we
The
have
benefit
the
comes
to
when
separate
we swap
the object
provider
out
the
which
onThe
the
creates
client
responsibility
Thewants
the
same
requested
aThis
request
service
for allows
theanother
connection,
logical
is
provided.
make,
connection
Inperhaps
the
from
provider
the
client.
object
us
to
one.
create
So the
The
client
interface
makes
then
thewith
request
returns
to
this
the
object
interface
between
passing
but
case
this
the
of
back
time
my
client
ahands
connection
a and
different
free,
the
provider.
itprovider
object
wants
or
to
Inserviced
identifier.
the
place
case of
(e.g.
objects
we
independent
one
phone
for
theanother)
code
orswap
object:
identifier
“place
to the
aofcall”
client.
myThis
hands-free,
This
the
way
the
that’s
a phone
(“a
client
different
the
can
call.
bluetooth
refer
phone”)
to
interface
the
platform
canrequest
be done
on
the
without
client
shutting
side,
and
down
(half
process
onthe
theclient
client,
it started
half
for
onsubsequent
the
providerfrom
calls.
– we’re
allows
to
the
evolve
system.
separately
the
dealing with concepts,
not
detailed implementation).
objects
it requests.
Copyright (C) 2005 by
Making sense?
Page 76
The Facade


Creating lots of powerful, focused objects
is a good thing, but systems can get large
enough where dealing many interfaces
becomes difficult.
The Facade inserts itself in between the
client(s) and all the objects, and provides
a unified interface into the subsystem.
F
a
c
a
d
e
Client
Classes
Copyright (C) 2005 by
Subsystem
Classes
Page 77
The Proxy



A Proxy is any object that ‘represents’ itself to be
another object.
There are a variety of reasons to do this, including
security, load management, and remote representation.
A good example of a proxy is a firewall. To the Internet,
the firewall “is” your system. But the firewall handles
flow control and security issues so that your system
doesn’t have to and isn’t exposed to the dangers of the
Internet.
System
Copyright (C) 2005 by
Security
Proxy
Page 78
Behavioral Patterns


Behavioral Patterns deal with algorithms
and the assignment of responsibilities
between objects. So it’s not just the
structure of the class and object
hierarchies, but how they communicate
and interact with one another.
Let’s take a look at three common
behavioral patterns:



The Command
The Iterator, and
The Observer
Copyright (C) 2005 by
Page 79
The Command




The concept behind the Command pattern is
to pass a ‘function’ to another object and have
it called from there.
For example, when we created our ‘Populate’
static method, we passed a pointer to a
function that added the Appt to the Storage
object. The command pattern is the object
oriented version of that concept
Where the function pointer is encapsulated
into an object and passed around like other
objects.
By placing the command into an object, you
can store the object, like putting it into a
queue of commands that the system must
address.
Copyright (C) 2005 by
Page 80
The Command




A good example of a Command pattern is and undo
operation
When the user changes an element on the display, you
first save the ‘state’ of the existing display – perhaps a
series of commands to ‘reset’ the current change to the
way it was – into an object. This ‘restore state’ command
object is then placed into an Undo stack.
You may push perhaps 5 of these items onto the stack.
When the user decides to undo all five, each element is
taken in turn and executed, putting back the ‘state’
where the previous undo can restore from.
EMPTY Undo Stack
Copyright (C) 2005 by
Display Controller
Object
Remove O
LEH
H
HELLO_
HELL_
HEL_
HE_
_ _ Does it make sense
how Command works?
Page 81
The Iterator


The iterator’s job is to sequentially
navigate a container while hiding the
underlying container implementation
We used iterators when we used Linq


No matter whether the data came from
internal objects or a database, we
accessed the data the same way
Iterators are very common in database
systems, and are also called cursors.
Copyright (C) 2005 by
Page 82
The Observer

Also known as Publish-Subscribe, the
Observer pattern has two parties



A simple example is a calendar’s reminder
option. You want to be reminded to leave in
time for this class , so you ‘subscribe’ to the
‘Notify’ list when the appointment’s time
comes up.


One who is interested about some event that can
or will occur (the subscriber), and
One who notifies interested parties that the
event has occurred (the publisher)
When the time arrives, the system advises you
with a reminder window.
We also discussed it when we discussed
events…the Broker Bill example

Let’s review that from an Observer pattern
viewpoint...
Copyright (C) 2005 by
Page 83
The Observer



A stock broker may (directly or indirectly)
allow you to ‘subscribe’ to a notification
service.
This service watches a particular stock,
and when it rises beyond a certain level,
the system ‘publishes’ that information by
notifying subscribers to pay attention to
the stock
This could be something as simple as
triggering an email to a mailing list, or be
a remote procedure executed over the
Internet – the implementationQuestions
isn’t
Does
Observer
on
essential to the pattern.
make
any
ofsense
the patterns
to
everyone?
we’ve
discussed?
Copyright (C) 2005 by
Page 84
End of Session
Advanced Language Concepts in C#
Last Update: 3/09
Page 85
Copyright (C) 2009 by David Figge. All Rights Reserved.
Descargar

Advanced Language Concepts in C#