Вы находитесь на странице: 1из 138



DAY 1 - GETTING STARTED ................................ ................................ ................................ ................................ ..... 6


       

 
       
     c     
   
            
          
      
       
Overview ................................ ................................ ................................ ................................ ......................... 9
Separation of Appearance and Behavior ................................ ................................ ................................ .......... 9
Rich composition ................................ ................................ ................................ ................................ ............. 9
Highly customizable ................................ ................................ ................................ ................................ ...... 10
Resolution independence................................ ................................ ................................ ............................... 10
    



      c


In Visual Studio 2008 ................................ ................................ ................................ ................................ ..... 10
   
 
      c
User Experience becomes a Key Success Factor ................................ ................................ .............................. 13
New Tools for Designers ................................ ................................ ................................ ................................ 13
Development Workflow of a WPF Project ................................ ................................ ................................ ...... 14
c 
    ................................ ................................ ................................ ................................ ... 15

    ................................ ................................ ................................ ............. 15
j    
      ................................ ................................ ................... 16
‰      ................................ ................................ ................................ ....................... 16
Î !  ................................ ................................ ................................ ................................ ............ 16
Roles ................................ ................................ ................................ ................................ ............................. 16
More Infos ................................ ................................ ................................ ................................ .................... 17

DAY 2 - CONCEPTS OF WPF ................................ ................................ ................................ ................................ .. 18

           c


Advantages of XAML ................................ ................................ ................................ ................................ ..... 18
XAML vs. Code................................ ................................ ................................ ................................ ............... 18
Properties as Elements ................................ ................................ ................................ ................................ .. 19
Implicit Type conversion ................................ ................................ ................................ ................................ 19
Markup Extensions ................................ ................................ ................................ ................................ ........ 19
Namespaces................................ ................................ ................................ ................................ .................. 20
         
Introduction ................................ ................................ ................................ ................................ .................. 21
Why do we need two different kind of trees? ................................ ................................ ................................ . 21
The Logical Tree ................................ ................................ ................................ ................................ ............ 21
The Visual Tree ................................ ................................ ................................ ................................ .............. 22
   "  #   
!  ................................ ................................ .................. 22
 
!

      
Introduction ................................ ................................ ................................ ................................ .................. 23
Value resolution strategy ................................ ................................ ................................ .............................. 24
The magic behind it ................................ ................................ ................................ ................................ ....... 24
How to create a DependencyProperty................................ ................................ ................................ ............ 25

 $% ................................ ................................ ................................ ............................... 26

c
 
$% ................................ ................................ ................................ ................................ .. 26
 $%................................ ................................ ................................ ................................ ....... 26
Readonly DependencyProperties ................................ ................................ ................................ ................... 27
Attached Properties................................ ................................ ................................ ................................ ....... 27
Listen to dependency property changes ................................ ................................ ................................ ......... 28
How to clear a local value................................ ................................ ................................ .............................. 29
        
How to Create a Custom Routed Event ................................ ................................ ................................ .......... 29

DAY 3 - LAYOUT AND CONTROLS................................ ................................ ................................ .......................... 31

    
!      c
Why layout is so important ................................ ................................ ................................ ............................ 31
Best Practices ................................ ................................ ................................ ................................ ................ 31
Vertical and Horizontal Alignment ................................ ................................ ................................ ................. 32
Margin and Padding................................ ................................ ................................ ................................ ...... 32
Height and Width ................................ ................................ ................................ ................................ .......... 32
Overflow Handling ................................ ................................ ................................ ................................ ........ 32
  ................................ ................................ ................................ ................................ ........................ 33
à  ................................ ................................ ................................ ................................ ........................ 33
Related Articles ................................ ................................ ................................ ................................ ............. 33
 
      
Introduction ................................ ................................ ................................ ................................ .................. 33
Define Rows and Columns ................................ ................................ ................................ ............................. 34
How to add controls to the grid ................................ ................................ ................................ ..................... 35
Resizable columns or rows ................................ ................................ ................................ ............................. 35
How to share the width of a column over multiple grids ................................ ................................ ................. 36

&  ................................ ................................ ................................ ................................ .................. 37
Using GridLenghts from code ................................ ................................ ................................ ......................... 37
More on this topic ................................ ................................ ................................ ................................ ......... 38

 
      
Introduction ................................ ................................ ................................ ................................ .................. 38
Stack Items horizontally ................................ ................................ ................................ ................................ 38
    
    

DAY 4 - DATABINDING AND UI A RCHITECTURE ................................ ................................ ................................ .... 41

  
     "c
Introduction ................................ ................................ ................................ ................................ .................. 41
DataContext ................................ ................................ ................................ ................................ .................. 42
ValueConverters ................................ ................................ ................................ ................................ ............ 42
   #  
#       
   "
What is a CollectionView? ................................ ................................ ................................ ............................. 44
How to Create and Use a CollectionView ................................ ................................ ................................ ....... 44
Navigation ................................ ................................ ................................ ................................ .................... 45
Filtering ................................ ................................ ................................ ................................ ........................ 46
Refresh the filter ................................ ................................ ................................ ................................ ........... 46
Sorting ................................ ................................ ................................ ................................ .......................... 46
Fast Sorting ................................ ................................ ................................ ................................ ................... 47
Grouping ................................ ................................ ................................ ................................ ....................... 47
How to create a CollectionView in XAML................................ ................................ ................................ ........ 48
     
     "

Introduction ................................ ................................ ................................ ................................ .................. 49
Introducing the Model-View-ViewModel pattern ................................ ................................ ........................... 49
    
    $
Implementing a ValidationRule (.NET 3.0 style) ................................ ................................ .............................. 50
Build a converter to convert ValidationErrors to a multi-line string ................................ ................................ . 52
Create an ErrorTemplate for the TextBox ................................ ................................ ................................ ....... 53
The ValidationRule and the ErrorTemplate in Action ................................ ................................ ...................... 54
How to manually force a Validation ................................ ................................ ................................ ............... 54
       $$
Introduction ................................ ................................ ................................ ................................ .................. 55
How to implement a ValueConverter ................................ ................................ ................................ ............. 55
How to use a ValueConverter in XAML ................................ ................................ ................................ ........... 56
Simplify the usage of ValueConvers ................................ ................................ ................................ ............... 56
StringFormat Converter ................................ ................................ ................................ ................................ . 57
       $
Introduction ................................ ................................ ................................ ................................ .................. 58
How to use behaviors in Expression Blend 3 ................................ ................................ ................................ ... 58
How does it work ................................ ................................ ................................ ................................ .......... 59
How to implement your own behavior ................................ ................................ ................................ ........... 60
List of some popular behaviors ................................ ................................ ................................ ...................... 61

DAY 5 - TEMPLATES AND STYLES ................................ ................................ ................................ .......................... 62

   
 
      
User Experience becomes a Key Success Factor ................................ ................................ .............................. 62
New Tools for Designers ................................ ................................ ................................ ................................ 62
Development Workflow of a WPF Project ................................ ................................ ................................ ...... 63
1. Elicit Requirements ................................ ................................ ................................ ................................ .... 64
2. Create and Validate UI Prototype................................ ................................ ................................ ............... 64
3. Implement Business Logic and Raw User Interface ................................ ................................ ..................... 65
4. Integrate Graphical Design ................................ ................................ ................................ ........................ 65
7
Roles ................................ ................................ ................................ ................................ ............................. 65
More Infos ................................ ................................ ................................ ................................ .................... 66
     ! 
    
Style inheritance................................ ................................ ................................ ................................ ............ 67
   
      
Introduction ................................ ................................ ................................ ................................ .................. 68
ContentPresenter ................................ ................................ ................................ ................................ .......... 69
What if a Binding working or a Setter is not applied when using a control template ................................ ....... 70
   
      
Introduction ................................ ................................ ................................ ................................ .................. 70
DataTemplates in Action: Building a simple PropertyGrid ................................ ................................ ............... 70
How to use a DataTemplateSelector to switch the Template depending on the data ................................ ...... 72
How to react to IsSelected in the DataTemplate ................................ ................................ ............................. 74

LOCALIZATION ................................ ................................ ................................ ................................ ..................... 75

     %       $


Different WPF translation mechanisms compared................................ ................................ .......................... 75
 %  


       


    $
The Idea ................................ ................................ ................................ ................................ ........................ 75

Other Implementations ................................ ................................ ................................ ................................ . 76
How to use it ................................ ................................ ................................ ................................ ................. 76
Implementation details of the translation infrastructure ................................ ................................ ................ 76

INTERACTION ................................ ................................ ................................ ................................ ....................... 83

       


Introduction ................................ ................................ ................................ ................................ .................. 83
How to use behaviors in Expression Blend 3 ................................ ................................ ................................ ... 83
How does it work ................................ ................................ ................................ ................................ .......... 84
How to implement your own behavior ................................ ................................ ................................ ........... 85
List of some popular behaviors ................................ ................................ ................................ ...................... 86
   

     
Drag&Drop in 6 Steps ................................ ................................ ................................ ................................ .... 87
Drag ................................ ................................ ................................ ................................ ............................. 87
Drop ................................ ................................ ................................ ................................ ............................. 89

RESOURCE ................................ ................................ ................................ ................................ ............................ 92

 
  
         
  
          "

2D GRAPHICS ................................ ................................ ................................ ................................ ....................... 96

   ! 
! 
     
Why do my lines appear so blurry? ................................ ................................ ................................ ................ 96
Resolution independence................................ ................................ ................................ ............................... 96
Align the edges not the center points ................................ ................................ ................................ ............. 97
Using SnapToDevicePixels for controls ................................ ................................ ................................ ........... 97
Using GuidelineSets for custom drawing ................................ ................................ ................................ ........ 97
Adjust the penwidth to the screen resolution ................................ ................................ ................................ . 98
    
        

  !          
  
     c
How to create a Thumbnail of an Image ................................ ................................ ................................ ...... 100
How to automatically crop an image ................................ ................................ ................................ ........... 101

3D GRAPHICS ................................ ................................ ................................ ................................ ..................... 104

    
      c"
3D Graphic Basics ................................ ................................ ................................ ................................ ........ 104
A world of triangles ................................ ................................ ................................ ................................ ..... 104
A right handed coordinate system ................................ ................................ ................................ ............... 105
Elements of a 3D scene ................................ ................................ ................................ ................................ 105
Hello 3D-World - A Simple Cube ................................ ................................ ................................ ................... 106

ANIMATION ................................ ................................ ................................ ................................ ....................... 108

  !  


       c
Common Errors ................................ ................................ ................................ ................................ ........... 108
        
     c

MULTIMEDIA ................................ ................................ ................................ ................................ ..................... 109

    
  !% 
    c

WINDOWS 7 ................................ ................................ ................................ ................................ ....................... 110


"
             cc
Introduction ................................ ................................ ................................ ................................ ................ 110
Extending the Glass ................................ ................................ ................................ ................................ ..... 110
          
   cc"
Introduction ................................ ................................ ................................ ................................ ................ 115
      &
   "        cc$
Introduction ................................ ................................ ................................ ................................ ................ 115
How to add a Task to the Jumplist ................................ ................................ ................................ ............... 116

INTEROPERABILITY ................................ ................................ ................................ ................................ ............. 118

How to get the Handle of a WPF Window ................................ ................................ ................................ .... 118

PERFORMANCE ................................ ................................ ................................ ................................ .................. 119

$

  
     cc
Application Startup ................................ ................................ ................................ ................................ ..... 119

EXPRESSION BLEND................................ ................................ ................................ ................................ ............ 120


  !
  
           c
Introduction ................................ ................................ ................................ ................................ ................ 120
The idea of SketchFlow ................................ ................................ ................................ ................................ 120
Workspace setup................................ ................................ ................................ ................................ ......... 121
Create a new SketchFlow project ................................ ................................ ................................ ................. 121
Create and connect screens ................................ ................................ ................................ ......................... 121
Drop sketchy controls onto screens ................................ ................................ ................................ .............. 122
Extract common parts to component screens................................ ................................ ............................... 123
Wire-up navigation ................................ ................................ ................................ ................................ ..... 124
Add sample data ................................ ................................ ................................ ................................ ......... 125
Add assets from Photoshop, Illustrator or PowerPoint................................ ................................ .................. 127
Test prototype and get feedback ................................ ................................ ................................ ................. 128
Generate prototype documentation ................................ ................................ ................................ ............ 130
   

  
 
    c
Introduction ................................ ................................ ................................ ................................ ................ 132
Preparing the Photoshop File................................ ................................ ................................ ....................... 132
Directly Import Photoshop Files in Expression Blend ................................ ................................ ..................... 133
How to convert Path to Resources ................................ ................................ ................................ ............... 134
Import Photoshop Files in Expression Design and Export to XAML ................................ ................................ 134

         c
Introduction ................................ ................................ ................................ ................................ ................ 136
Popular Addins ................................ ................................ ................................ ................................ ............ 136
How to Load and Run an AddIn................................ ................................ ................................ .................... 136

TOOLS ................................ ................................ ................................ ................................ ................................ 137

        c


    
      c
        c
 

      c

$
Day 1 - Getting Started

Ôearn WPF in one Week


I started to build a onw week training course to learn WPF. Starting with the basics and going
through the important concepts of the framework up to more complex topics. I hope you like it.

'( c )**+,- .*'/*)0


Install the development tools

Learn the basic concepts of WPF

Create your first WPF application

Learn how WPF changed the development workflow

'(  1,2)3*. 14

Get an introduction to XAML

Learn about the hierarchical relation of elements in WPF

Find out about the magic behind DependencyProperties

Get familiar with routed events.

'(  '(15* ',0 1,*/16.


Learn the layout basics

See the grid layout panel in action

Stack elements with the stackpanel

Get an overview about the variety of included controls.

Have a look at 3rd-party libraries


'( " '*'+,0+,- ',0  /27+*)2*5/)
Introduction to WPF DataBinding

How to display, sort and filter data

Using the Model-View-ViewModel Pattern

Learn how to validate user input

Create your own ValueConverter

Enhance the MVVM pattern by using Behaviors and Actions

'( $ )836'*). ',0 *(6).


Learn how to build rich user experience with WPF

Style the appearance of your controls

Completely replace the look of a control

How to display complex data in lists by using DataTemplates.

WPF Development Tools


Microsoft provides two development tools for WPF applications. One is @isual Studio, made for
developers and the other is Expression Blend made for designers. While Visual Studio is good
in code and XAML editing, it has a rare support for all the graphical stuff like gradients, template
editing, animation, etc. This is the point where Expression Blend comes in. Blend covers the
graphical part very well but it has (still) rare support for code and XAML editing.

So the conclusion is that you will need both of them.

á  
  
Visual Studio is the tool for developers to develop WPF applications. It includes a graphical
designer for WPF since version 2008. If you're using Visual Studio 2005 you can install an add -
on that enables you to develop WPF applications.

Microsoft provides a free Express Edition of Visual Studio that also includes the WPF designer.
You can download it from the following URL


Download Microsoft Visual C# 2010 - Express Edition

á      


Expression Blend is the tool for designers. It's part of the Expression Studio, a new tool suite
from Microsoft especially created for user experience designers. Blend covers all the missing
features of the Visual Studio designer like styling, templating, animations, 3D gr aphics, resources
and gradients.

In the latest Version it also includes a powerful prototyping tool called SketchFlow. Expression
Blend can open solution files created by visual studio.

Download Microsoft Expression Blend 3

   


è‘ Snoop (Inspect the Visual Tree of running WPF applications)
è‘ Mole (Data Visualizer for Visual Studio
è‘ XAML Power Toys
è‘ WPF Performance Suite


ntroduction to Windows Presentation Foundation
 

The Windows Presentation Foundation is Microsofts next generation UI framework to create


applications with a rich user experience. It is part of the .NET framework 3.0 and higher.

WPF combines application UIs, 2D graphics, 3D graphics, documents and mul timedia into one
single framework. Its vector based rendering engine uses hardware acceleration of modern
graphic cards. This makes the UI faster, scalable and resolution independent.

The followinig illustration gives you an overview of the main new featur es of WPF



 


 
 

WPF separates the appearance of an user interface from its behavior. The appearance is
generally specified in the Extensible Application Markup Language (XAML), the behavior is
implemented in a managed programming language like C# or Visual Basic. The two parts are
tied together by databinding, events and commands. The separation of appearance and
behavior brings the following benefits:

è‘ Appearance and behaviour are loosely coupled


è‘ Designers and developers can work on separate models.
è‘ Graphical design tools can work on simple XML documents instead of parsing code.

÷    

Controls in WPF are extremely composable. You can define almost any type of controls as
content of another. Although these flexibility sounds horrible to designers, its a very powerful


feature if you use it appropriate. Put an image into a button to create an image button, or put a
list of videos into a combobox to choose a video file.

m 
m
   
m   
  
m  
  !"
m
 
m 

ë ! "  #
$ 

Because of the strict separation of appearance and behavior you can easily change the look of a
control. The concept of styles let you skin controls almost like CSS in HTML. Templates let you
replace the entire appearance of a control.

The following example shows an default WPF button and a customized button.

÷     

All measures in WPF are logical units - not pixels. A logical unit is a 1/96 of an inch. If you
increase the resolution of your screen, the user interface stays the same size - if just gets
crispier. Since WPF builds on a vector based rendering engine it's incredibly easy to build
scaleable user interfaces.

ëow to create a simple WPF application


 
  %

Open Visual Studio 2008 and choose "File", "New", "Project..." in the main menu. Choose "WPF
Application" as project type.

Choose a folder for your project and give it a name. Then press "OK"
c
Visual Studio creates the project and automatically adds some files to the solution. A
Window1.xaml and an App.xaml. The structure looks quite similar to WinForms, except that the
"#$"    file is no longer code but it's now declared in XAML as
"#$ 

Open the "#$  file in the WPF designer and drag a Button and a TextBox from the
toolbox to the Window

cc
Select the Button and switch to the event view in the properties window (click on the little
yellow lightning icon). Doubleclick on the "Click" event to create a method in the codebehind
that is called, when the user clicks on the button.

Êote: If you do not find a yellow lightning icon, you need to install the Service Pack 1 for
@isualStudio on your machine. Alternatively you can doubleclick on the button in the
designer to achieve the same result.

Visual Studio automatically creates a method in the code-behind file that gets called when the
button is clicked.
½ %$&' 
( 
 " )* "+, - .
/
   $   012
3
The textbox has automatically become assigned the name    $ by the WPF designer. Set
text Text to "Hello WPF!" when the button gets clicked and we are done! Start the application by
hit [F5] on your keyboard.

c
Isn't this cool!

—ser Experience Design Process


— $ 
&" 


In the past, we focused mainly on building products that fulfilled the functional requirements of
the user. User experience was often considered late in the development process. But today the
customer demands more than just a working product. Providing the right features is still the
prerequisite for a good product, but to turn it into something extraordinary you need to provide
a good user experience!

Providing a rich user experience is not a thing of fortune. It needs to be planed, designed and
integrated into the development of a product. Designing a rich user experience is not only
about make up your user interface by some graphics and gradients - its a much broader
concept. Its about creating an emotional connection between the user and your software. It
makes the user feel good and so he likes to continue using the software.

Ê' ( !

Microsoft recognized, give development teams the power to create rich user experiences it
needs a lot more graphical tool support than VisualStudio can provide today. So they decided to
create a new tool suite - made for designers.

c
This tool suite is called áicrosoft Expression. It consists of the four products:

è‘ Expression Blend is built to create user interfaces in WPF and Silverlight. It builds the
bridge between designer and developers. It can open VisualStudio solutions
è‘ Expression Design is a leightweight version of Adobe Illustrator to create and edit
vector graphics.
è‘ Expression áedia is built to encode, cut and enrich video files and optimize them for
silverlight streaming
è‘ Expression Web is Microsoft next generation of HTML and Javascript editor. Its the
replacement for Frontpage.

Together they are a powerful package. The following illustration shows a sample workflow of
integrating a vector image that is created by a graphics designer in Adobe Illustrator into a WPF
project that is part of a VisualStudio solution.

(  ) 


)**+ 

c"
Developing a WPF application with a rich user experience requires a lot more skills than just a
requirements analyst that defines a list of use cases and developer that implements the
software. You have to find out what the user really needs. This can be done by following a user
centered approach.

1. Elicit Requirements

Like in any kind of software projects its important to know and focus the target of your
development. You should talk to stakeholders and users to find out the real needs. These needs
should be refined to features and expressed in use cases (abstract) or user scenarios
(illustrative). Priorize the tasks by risk and importance and work iteratively. This work is done by
the role of the requirements engineer.

2. Create and Validate UI Prototype

Creating a user interface prototype is an important step to share ideas between users and
engineers to create a common understanding of the interaction design. This task is typically
done by an interaction designer. It's helpful to only sketch the user int erface in a rough way to
prevent early discussions about design details. There are multiple techniques and tools to do
this. Some of them are:

è‘ Paper prototype
Use paper and pencil to draw rough sketches of your user interface. No tools and
infrastructure is needed. Everyone can just scribble thier ideas on the paper.
è‘ Wireframes
Wireframes are often used to sketch the layout of a page. It's called wireframes because
c$
you just draw the outlines of controls and images. This can be done with tools like
PowerPoint or Visio
è‘ Expression Blend 3 - Sketch Flow Sketch flow is a new cool feature to create interactive
prototypes directly in WPF. You can use the integrated "wiggly style" to make it look
sketchy. The prototype can be run in a standalone player that has an integrated feedback
mechanism.
è‘ Interactive Prototype The most expensive and real approach is to create an (reusable)
interactive prototype that works as the real application but with dummy data.

It is strongly recommended to test your UI prototype on real users. This helps you to find out
and address design problems early in the development process. The following techniques are
very popular to evaluate UI prototypes:

è‘ Walktrough
A walktrough is usually done early in a project with wireframes or paper proto types. The
user gets a task to solve and he controlls the prototype by touching on the paper. The
test leader than presents a new paper showing the state after the interaction.
è‘ —sability Lab
To do a usability lab, you need a computer with a screen capture software and a camera.
The proband gets an task to do and the requirements and interaction engineer watch
him doing this. They should not talk to him to find out where he gets stuck and why.

3. Implement Business Logic and Raw User Interface

4. Integrate Graphical Design

5. Test software

÷ 

Buliding a modern user interface with a rich user experience requires additional skills from your
development team. These skills are described as roles that can be distributed among peoples in
your development team.

è‘ Developer
The developer is responsible to implement the functionality of the application. He
creates the data model, implements the business logic and wires all up to a simple view.
è‘ „raphical Designer
The graphical designer is responsible to create a graphical concept and build graphical
assets like icons,logos, 3D models or color schemes. If the graphical designer is familiar
with Microsoft Expression tools he directly creates styles and control templates.
è‘ Interaction Designer
The interaction designer is responsible for the content and the flow of a user interface.
c
He creates wireframes or UI sketches to share its ideas with the team or customer. He
should validate his work by doing walktroughs or storyboards.
è‘ Integrator
The integrator is the artist between the designer and the developer world. He takes the
assets of the graphical designer and integrates them into the raw user interface of the
developer. This role needs a rare set of skills and so it's often hard to find the right
person for it.

á

The New Iteration - Microsoft Paper about the Designer/Developer collaboration

c
Day 2 - Concepts of WPF

ntroduction to XAMÔ
XAML stands for Extensible Application Markup Language. Its a simple language based on XML
to create and initialize .NET objects with hierarchical relations. Altough it was originally invented
for WPF it can by used to create any kind of object trees.

Today XAML is used to create user interfaces in WPF, Silverlight, declare workflows in WF and
for electronic paper in the XPS standard.

All classes in WPF have parameterless constructors and make excessive usage of properties. That
is done to make it perfectly fit for XML languages like XAML.

 

!,á-

All you can do in XAML can also be done in code. XAML ist just another way to create and
initialize objects. You can use WPF without using XAML. It's up to you if you want to declare it in
XAML or write it in code. Declare your UI in XAML has some advantages:

è‘ XAML code is short and clear to read


è‘ Separation of designer code and logic
è‘ Graphical design tools like Expression Blend require XAML as source.
è‘ The separation of XAML and UI logic allows it to clearly separate the roles of designer
and developer.

,á-./ 

As an example we build a simple StackPanel with a textblock and a button in XAML and
compare it to the same code in C#.
m
 
m  
456    "7-48 m  

m 4$6 -   *9m 
m
 
The same expressed in C# will look like this:



'   


 

 
   
 (.2
  ' 
 2
'     


c
  
  
    
(.2
  
4 
 ($6.2
  
     "7-48 2

 ' " -""(  
.2
'     
%   (.2
%4 
 (56.2
%' 92

 ' " -""(%.2
As you can see is the XAML version much shorter and clearer to read. And that's the power of
XAMLs expressiveness.

* 
  

Properties are normally written inline as known from XML m ' 9 . But
what if we want to put a more complex object as content like an image that has properties itself
or maybe a whole grid panel? To do that we can use the property element syntax. This allows us
to extract the property as an own chlild element.
m 
m '  
m   9 ":6 :6
m '  
m 

   '" 

A very powerful construct of WPF are implicit type converters. They do their work silently in the
background. When you declare a BorderBrush, the word "Blue" is only a string. The implicit
',   makes a ! "#4 "    out of it. The same
regards to the border thickness that is beeing converted implicit into a 
  object. WPF
includes a lot of type converters for built-in classes, but you can also write type converters for
your own classses.
m "  "     " 
 6)$6
m " 

á
  

Markup extensions are dynamic placeholders for attribute values in XAML. They resolve the
value of a property at runtime. Markup extensions are surrouded by curly braces (Example:

"/ *  ; 
" 3 ). WPF has some built -in
markup extensions, but you can write your own, by deriving from 4
+   . These
are the built-in markup extensions:

è‘ Binding
To bind the values of two properties together.

c
è‘ StaticResource
One time lookup of a resource entry
è‘ DynamicResource
Auto updating lookup of a resource entry
è‘ ›emplateBinding
To bind a property of a control template to a dependency property of the control
è‘ x:Static
Resolve the value of a static property.
è‘ x:Êull
Return 

The first identifier within a pair of curly braces is the name of the extension. All preciding
identifiers are named parameters in the form of Property=Value. The following example shows a
label whose '  is bound to the   of the textbox. When you type a text into the text
box, the text property changes and the binding markup extension automatically updates the
content of the label.
m    <;    
m8% ' / " )+  ;    3 

Ê



At the beginning of every XAML file you need to include two namespaces.
The first is <    # 566=     . It is
mapped to all wpf controls in ! "#'  .
The second is <    #  566=  it is mapped to
! "#4
 that defines the XAML keywords.
The mapping between an XML namespace and a CLR namespace is done by the
7 >  attribute at assembly level. You can also directly include a CLR namespace
in XAML by using the ?  < prefix.


m"#
 @<    # 566=    @ 
  < @<    # 566=  @ 
m"#

Ôogical- and Visual Tree


  

Elements of a WPF user interface are hierarchically related. This relation is called the
Logical›ree. The template of one element consists of multiple visual elements. This tree is called
the @isual›ree. WPF differs between those two trees, because for some problems you only need
the logical elements and for other problems you want all elements.
m"#
mA"
m8% ' 8% 
m '  
mA"
m"#

)"     0

A WPF control consists of multiple, more primitive controls. A button - for example - consists of
a border, a rectangle and a content presenter. These controls are visual children of the button.
When WPF renders the button, the element itself has no appearance, but it iterates through the
visual tree and renders the visual children of it. This hierarchical relation can also be used to do
hit-testing, layout etc.
But sometimes you are not interested in the borders and rectangles of a controls' template.
Particulary because the template can be replaced, and so you should not relate on the visual
tree structure! Because of that you want a more robust tree that only contains the "real" controls
- and not all the template parts. And that is the eligibility for the logi cal tree.

'-! 
'

c
The logical tree describes the relations between elements of the user interface. The logical tree
is responsible for:

è‘ Inherit DependencyProperty values


è‘ Resolving >! *   references
è‘ Looking up element names for bindings
è‘ Forwaring RoutedEvents

' 
'

The visual tree contains all logical elements including all visual elements of the template of
each element.<BR

The visual tree is responsible for:

è‘ Rendering visual elements


è‘ Propagate element opacity
è‘ Propagate Layout- and RenderTransforms
è‘ Propagate the +% " property.
è‘ Do Hit-Testing
è‘ RelativeSource (FindAncestor)

Programmatically Find an Ancestor in the Visual Tree

If you are a child element of a user interface and you want to access data from a parent element,
but you don't know how many levels up that elemens is, it's the best solution to navigate up the
tree until it finds an element of the requested type.

This helper does excactly this. You can use almost the same code to navigate through the logical
tree.
½
 

 B    +   
/
½
 
0"-  m(>  "  !%C "  "  !%C  .
#  <
 
/
>  "  !%C   "  "  !%C 2 

/
 B     A   ( .2
3
 ( 1DD1(  ..2
    2
3


3
The following example shows how to use the helper. It starts at  and navigates up the
visual tree until it finds an element of type A". If the helper reaches the root element of the
tree, it returns  .
,"B    +   0"- mA"(  .2

Dependency Properties
Introduction

Value resolution strategy

The magic behind it

How to create a DepdencyProperty

Readonly DependencyProperties

Attached DependencyProperties

Listen to dependency property changes

How to clear a local value

  

When you begin to develop appliations with WPF, you will soon stumble across
DependencyProperties. They look quite similar to normal .NET properties, but the concept
behind is much more complex and powerful.

The main difference is, that the value of a normal .NET property is read directly from a private
member in your class, whereas the value of a DependencyProperty is resolved dynamically
when calling the A B  (. method that is inherited from DependencyObject.
When you set a value of a dependency property it is not stored in a field of your object, but in
a dictionary of keys and values provided by the base class >  "  !%C  . The key of an
entry is the name of the property and the value is the value you want to set.
The advantages of dependency properties are

è‘ Reduced memory footprint


It's a huge dissipation to store a field for each property when you think that over 90% of
the properties of a UI control typically stay at its initial values. Dependency properties
solve these problems by only store modified properties in the instance. The default
values are stored once within the dependency property.

è‘ @alue inheritance
When you access a dependency property the value is resolved by using a value
resolution strategy. If no local value is set, the dependency property navigates up the


logical tree until it finds a value. When you set the FontSize on the root element it
applies to all textblocks below except you override the value.

è‘ ihange notification
Dependency properties have a built-in change notification mechanism. By registering a
callback in the property metadata you get notified, when the value of the property has
been changed. This is also used by the databinding.


  
!"

Every time you access a dependency property, it internally resolves the value by following the
precedence from high to low. It checks if a local value is available, if not if a custom style trigger
is active,... and continues until it founds a value. At last the default value is always available.

'
! $   

Each WPF control registers a set of >  "  !    to the static
>  "  !  ! class. Each of them consists of a key - that must be unique per type -
and a metadata that contain callbacks and a default value.
All types that want to use >  "  !    must derive from >  "  !%C  .
This baseclass defines a key, value dictionary that contains local values of dependency
properties. The key of an entry is the key defined with the dependency property.
When you access a dependency property over its .NET property wrapper, it internally calls
A B  (>  "  !  !. to access the value. This method resolves the value by
using a value resolution strategy that is explained in detail below. If a local value is available, it
reads it directly from the dictionary. If no value is set if goes up the logical tree and searches for
an inherited value. If no value is found it takes the default value defined in the property
metadata. This sequence is a bit simplified, but it shows the main concept.

"
ë

( "*"

To create a DependencyProperty, add a static field of type > "  !  ! to your type
and call >  "  !  !*  (. to create an instance of a dependency property.
The name of the DependendyProperty must always end with ...Property. This i s a naming
convention in WPF.
To make it accessable as a normal .NET property you need to add a property wrapper. This
wrapper does nothing else than internally getting and setting the value by using the GetValue()
and SetValue() Methods inherited from DependencyObject and passing the
DependencyProperty as key.

Important: Do not add any logic to these properties, because they are only called when
you set the property from code. If you set the property from XAáL the Set@alue() method
is called directly.

If you are using Visual Studio, you can type " and hit 2x tab to create a dependency
property.
>  "  !  ! 
½
 
 >  "  !  !'   ! 
>  "  !  ! *  ('  )½(>  .)
½(4!' 
' .) 
0 #
 !4 " (>  ;#..2
;+  !#  
½
>  '  
/
$
 /  (>  .A B  ('   ! .23
 / B  ('   !),  .23
3
Each DependencyProperty provides callbacks for change notification, value coercion and
validation. These callbacks are registered on the dependency property.
 0 #
 !4 " (>  ;#)
 '   !' ") 

 '  '   ! .)


 B " '   ! .2

Value Changed Callback

The change notification callback is a static method, that is called everytime when the value of
the TimeProperty changes. The new value is passed in the EventArgs, the object on which the
value changed is passed as the source.
½  
'   !' " (>  "  !%C 
 )
>  "  !  !' "+, - .
/
4!' 
'      4!' 
' 2 
>    (>  . ; #B  2
  "      
3

Coerce Value Callback

The coerce callback allows you to adjust the value if its outside the boundaries without throwing
an exception. A good example is a progress bar with a Value set below the Minimum or above
the Maximum. In this case we can coerce the value within the allowed boundaries. In the
following example we limit the time to be in the past.
½  
 
'    ! (>  "  !%C  " )
 
".
/
((>  .">  ;#.
/
">  ;#2
3
  "2
3

Validation Callback


In the validate callback you check if the set value is valid. If you return false, an
ArgumentException will be thrown. In our example demand, that the data is an instance of a
>  .
½  
B "   ! ( 
".
/
  " >  2
3

÷
 "( "* 

Some dependency property of WPF controls are readonly. They are often used to report the
state of a control, like the 4 ,  property. Is does not make sense to provide a setter
for this value.
Maybe you ask yourself, why not just use a normal .NET property? One important reason is that
you cannot set triggers on normal .NET propeties.
Creating a read only property is similar to creating a regular DependencyProperty. Instead of
calling >  "  !  !*  (. you call
>  "  !  !*  * " !(. . This returns you a
>  "  !  !9 ! . This key should be stored in a private or protected static readonly
field of your class. The key gives you access to set the value from within your class and use it like
a normal dependency property.
Second thing to do is registering a public dependency property that is assigned to
>  "  !  !9 !>  "  !  ! . This property is the readonly property
that can be accessed from external.
*   , 
!  ,  
½  
 >  "  !  !9 !4 ,   !9 ! 
>  "  !  ! *  * " ! (4 ,  )
½(.)½(4!' .)
 0 #
 !4 " ( ..2
*   %   !  ,  
½
 
 >  "  !  !4 ,   ! 
4 ,   !9 ! >  "  !  ! 2
;+  !#  
½
4 , 
/
 /  (.A B  (4 ,   ! .23
½  / B  (4 ,   !9 !),  .23
3


 * 

Attached properties are a special kind of DependencyProperties. They allow you to attach a
value to an object that does not know anything about this value.


A good example for this concept are layout panels. Each layout panel needs different data to
align its child elements. The Canvas needs  and 8 , The DockPanel needs Dock, etc. Since
you can write your own layout panel, the list is infinite. So you see, it's not possible to have all
those properties on all WPF controls.
The solution are attached properties. They are defined by the control that needs the data from
another control in a specific context. For example an element that is aligned by a parent layout
panel.

To set the value of an attached property, add an attribute in XAML with a prefix of the element
that provides the attached property. To set the the Canvas.Top and Canvas.Left property of a
button aligned within a Canvas panel, you write it like this:
m',
m ',56',8 56' ' 
 1
m',
½
 
 >  "  !  !  ! 
>  "  !  ! *  -  " ()
½(.)½(',.)
 0 #
 !4 " (6")
0 #
 !4 "  ..2
½
 
 (+    ) ,  .
/
   B  (  !),  .2
3
½
 
A (+     .
/
  (.  A B  (  !.2
3

-   ""


!

If you want to listen to changes of a dependency property, you can subclass the type that
defines the property and override the property metadata and pass an PropertyChangedCallback.
But an much easier way is to get the >  "  !  !>   and hookup a
callback by calling -""B  ' "(.


>  "  !  !>   >   >  "  !  !>   
0  !(      !)½(   ..2
( >  1.
/
 >  -""B  ' "(!   )
/
-""! !  "     


3.2
3

ë 

 



Because  is also a valid local value, there is the constant


>  "  !  ! B  that describes an unset value.
%$' B  ( '   !.2

÷outed Events

Routed events are events which navigate up or down the visual tree acording to their
* !. The routing strategy can be bubble, tunnel or direct. You can hook up
event handlers on the element that raises the event or also on other elements above or below it
by using the attached event syntax: ' 
 &' 
 .
Routed events normally appear as pair. The first is a tunneling event called
 , #4 ># and the second is the bubbling called 4 >#. They don't stop
routing if the reach an event handler. To stop routing then you have to set " "
 2
è‘ ›unneling The event is raised on the root element and navigates down to the visual tree
until it reaches the source element or until the tunneling is stopped by marking the
event as handeld. By naming convention it is called  , # and appears before
corresponding bubbling event.
è‘ Bubbling The event is raised on the source element and navigates up to the visual tree
until it reaches the root element or until the bubbling is stopped by marking the event as
handled. The bubbling event is raised after the tunneling event.

è‘ Direct The event is raised on the source element and must be handled on the source
element itself. This behavior is the same as normal .NET events.

ë/

/  ÷  

*    " ,  
½
 
 * "+,   "+,  
+, 4 *  * "+,  (  ")
* ! %% )
½(* "+, "  .)½(4!'' ..2


;+# 
½
* "+, "   " 
/
""/-""" (  "+, ),  .23
 , /* , "  (  "+, ),  .23
3
*   " ,   " 
* +, ( * "+, - (4!''    "+, ..2


Day 3 - Ôayout and Controls

ntroduction to WPF Ôayout


Why layout is so important

Best Practices

Vertical and Horizontal Alignment

Margin and Padding

Width and Height

Content Overflow Handling

)"
"   


Layout of controls is critical to an applications usability. Arranging controls based on fixed pixel
coordinates may work for an limited enviroment, but as soon as you want to use it on different
screen resolutions or with different font sizes it will fail. WPF provides a rich set built -in layout
panels that help you to avoid the common pitfalls.

These are the five most popular layout panels of WPF:

è‘ Grid Panel
è‘ Stack Panel
è‘ Dock Panel
è‘ Wrap Panel
è‘ Canvas Panel

*
 

è‘ Avoid fixed positions - use the -   properties in combination with 4 to
position elements in a panel
è‘ Avoid fixed sizes - set the " and   of elements to - whenever possible.
è‘ Don't abuse the canvas panel to layout elements. Use it only for vector graphics.
è‘ Use a StackPanel to layout buttons of a dialog
è‘ Use a GridPanel to layout a static data entry form. Create a Auto sized column for the
labels and a Star sized column for the TextBoxes.

c
è‘ Use an ItemControl with a grid panel in a DataTemplate to layout dynamic key value lists.
Use the SharedSize feature to synchronize the label widths.

 

 ë #
 ! 

Use the B   -   and  -  properties to dock the controls
to one or multiple sides of the panel. The following illustrations show how the sizing behaves
with the different combinations.

á
! 
 *
!

The 4 and "" properties can be used to reserve some space around of within the
control.

è‘ The 4 is the extra space around the control.


è‘ The "" is extra space inside the control.
è‘ The "" of an outer control is the 4 of an inner control.

ë !
 ) 

Alltough its not a recommended way, all controls provide a   and " property to give
an element a fixed size. A better way is to use the 4 , 4  , 4" and
4 " properties to define a acceptable range.
If you set the width or height to - the control sizes itself to the size of the content.

 ë
 !


Clippin
  
Ô y t  ty  y t   t
    tt t
   t 
 
 t  .
  
 
t
 yttt i 

 tyt
t 
 .

à ollin

W t 
ttt

t
 tt    z,y
  tt
 à   . 

V t

 t


t   .


  ty
 t  
     
t
  y t   t   
z
t 
à   
 
 t.
à   
à  
i 
 
i à   
i   
à  
à   

÷    

á- Ô y
tyt

„ri P
t
t



t
  
  



t
 
t
t
t   

Rz





t
 t  t 
 

 t  

  Ô t





 




The grid is a layout panel that arranges its child controls in a tabular structure of rows and
columns. Its functionality is similar to the HTML table but more flexible. A cell can contain
multiple controls, they can span over multiple cells and even overlap themselves.

The resize behaviour of the controls is defined by the  -   and
B   -   properties who define the anchors. The distance between the anchor
and the grid line is specified by the margin of the contr ol

( ÷
 / 

The grid has one row and column by default. To create additional rows and columns, you have
to add *#>  items to the *#>  collection and ' > 
items to the ' >  collection. The following example shows a grid with three
rows and two columns.
The size can be specified as an absolute amount of logical units, as a percentage value or
automatically.

Fixed size of logical units (1/96 inch)

Takes as much space as needed by the contained control

Takes as much space as available, percentally divided over all star-sized columns.
Star-sizes are like percentages, except that the sum of all star columns does not
have to be 100%. Remember that star-sizing does not work if the grid size is
calculated based on its content.

mA"
mA"*#>  
m*#>  -
m*#>  -
m*#>  E
m*#>  5F
mA"*#>  
mA"' >  

"
m' >  "-
m' >  "566
mA"' >  
mA"

ë
 ! 

To add controls to the grid layout panel just put the declaration between the opening and
closing tags of the A". Keep in mind that the row- and columndefinitions must precced any
definition of child controls.
The grid layout panel provides the two attached properties A"'  and A"*# to
define the location of the control.
mA"
mA"*#>  
m*#>  -
m*#>  -
m*#>  E
m*#>  5F
mA"*#>  
mA"' >  
m' >  "-
m' >  "566
mA"' >  
m8% A"*#6A"' 6' ; <
m8% A"*#$A"' 6' +?4 <
m8% A"*#5A"' 6' ' <
m   A" ' $A"*#64G
m   A" ' $A"*#$4G
m   A" ' $A"*#54G
m A"' $A"*#G -   *
4"F64G'  "
mA"

÷ #
$  

$
WPF provides a control called the A"  . This control is added like any other control
to a cell of the grid. The special thing is that is grabs itself the nearest gridline to change its
width or height when you drag this control around.
mA"
mA"' >  
m' >  "E
m' >  "-
m' >  "E
mA"' >  
m8% ' 8 A"' 6
mA"    -   *
 B   -     
 A"' $*  ,  ,-";  
 ": 
"H00 ' ' '
m8% ' *A"' 5
mA"
The best way to align a grid splitter is to place it in its own auto -sized column. Doing it this way
prevents overlapping to adjacent cells. To ensure that the grid splitter changes the size of the
previous and next cell you have to set the *  , to  ,-";  .
The splitter normally recognizes the resize direction according to the ratio between its height
and width. But if you like you can also manually set the *  >  to '  or
*#.
mA"   *  > ' 

ë
 
    ! 

The shared size feature of the grid layout allows it to synchronize the width of columns over
multiple grids. The feature is very useful if you want to realize a multi -column listview by using a
grid as layout panel within the data template. Because each item contains its own grid, the
columns will not have the same width.

By setting the attached property A" "   to  on a parent element


you define a scope within the column-widths are shared.

To synchronize the width of two columndefinitions, set the  " A to the same
name.
m ' A"  "    
m '      
m>   
mA"
mA"' >  
m' >   " A 0'  
"-
m' >  "E
mA"' >  
m  
 / " 9 !3   
m  
 / " B  3 A"' $
 
mA"
m>   
m '      
m ' 

Useful Hints

Columns and rows that participate in size-sharing do not respect Star sizing. In the size-sharing
scenario, Star sizing is treated as Auto. Since TextWrapping on TextBlocks within an SharedSize
column does not work you can exclude your last column from the shared size. This often helps
to resolve the problem.

— !1 -!  

If you want to add columns or rows by code, you can use the A"8  class to define the
differenz types of sizes.

A"8 - ‘
‘
A"" A"(.2


' >   $  ' > (.2


 $"A"8 -2
' >   5  ' > (.2
 5" A"8 ($)A"!  .2


"' >  -""(  $.2


"' >  -""(  5.2


á  

How to create a resizable column

WPF StackPanel

  

The 
 in WPF is a simple and useful layout panel. It stacks its child elements below
or beside each other, dependening on its orientation. This is very useful to create any kinds of
lists. All WPF  '  like '%  , 8  or 4  use a StackPanel as their
internal layout panel.
m
 
m  
4$60 56#"! 
!
 Im  

m 4$6 
m 
m 4$6
m 
m 4$68   m 
m 4$6' m 
m
 


  #
"

A good example for a horizontal stack panel are the "OK" and "Cancel" buttons of a dialog
window. Because the size of the text can change if the user changes the font -size or switches the
language we should avoid fixed sized buttons. The stack panel aligns the two buttons
depending on their desired size. If they need more space they will get it automatically. Never
mess again with too small or too large buttons.


m
 4F  
m 4"JG9m 
m 4"JG4$6)6)6)6' m 
m
 

Ouilt-in Controls of WPF


The WPF framework provides a rich set of built-in controls. The controls can be devided in the
following categories.

Fixed

Auto

Star (*)

Auto sized


Star sized

 #A"8 ($)A"! .

Fixed size

 #A"8 ($66)A"!   .

Third Party Controls

DataGrid

ItemsControl

LivePreview ComboBox

Dialogs

Slider

Popup

RadioButton

ToolTips

TextBox

Menus

Expander

PasswordBox

ContextMenu

Calendar

ListBox

ListView

Window

"
Day 4 - DataOinding and —
Architecture

(

  ! )*

  

WPF provides a simple and powerful way to auto-update data between the business model
and the user interface. This mechanism is called DataBinding. Everytime when the data of your
business model changes, it automatically reflects the updates to the user interface and vice
versa. This is the preferred method in WPF to bring data to the user interface.

Databinding can be unidirectional (source -> target or target <- source), or bidirectional
(source <-> target).

The source of a databinding can be a normal .NET property or a DependencyProperty. The


target property of the binding must be a DependencyProperty.

To make the databinding properly work, both sides of a binding must provide a change
notification that tells the binding when to update the target value. On normal .NET properties
this is done by raising the  !' " event of the   ½  
interface. On DependencyProperties it is done by the PropertyChanged callback of the property
metadata

Databinding is typically done in XAáL by using the Ú  markup extension. The
following example shows a simple binding between the text of a TextBox and a Label that
reflects the typed value:

m
 

m    <;  

m8% ' / " )+  ;  ) 

"c
 "     !' "3 

m
 

(

/

Every WPF control derived from 0 #


+   has a >'  property. This
property is meant to be set to the data object it visualizes. If you don't explicity define a
source of a binding, it takes the data context by default.

The >'  property inherits its value to child elements. So you can set the
>'  on a superior layout container and its value is i nherited to all child elements. This
is very useful if you want to build a form that is bound to multiple properties of the same data
object.

m
 >' / *  !' 3 

m    / "0; 3 

m    / "8; 3 

m    / " 3 

m    / "'!3 

m
 


/

If you want to bind two properties of different types together, you need to use a
@alueionverter. A ValueConverter converts the value from a source type to a target type and
back. WPF already includes some value converters but in most cases you will need to write your
own by implementing the B  ',   interface.

A typical example is to bind a boolean member to the B% ! property. Since the visibility
is an enum value that can be B% , '  " or "" , you need a value converter.

m
 

m
 *   

m  B% !',   <9 !% B

m
 *   



m'
  <;  
#>   ' #>  

m
  <; "    

 B% !/ "'


")
+  ;  
#>  ) 
"
 ',  / *  % B33 

m
 

m
 

The following example shows a simple converter that converts a boolen to a visibility property.
Note that such a converter is already part of the .NET framework.

½

   B% !',   <B  ',  

/

½
 
', ( 
,  )!  ! )  

  )

 '     .

/

(,     .

/

  ((.,  .IB% !B% <


B% !'  "2

3

  ,  2

3

½
 
',  
( 
,  )!  ! )  

  )

 '     .

/

   ;   "+  (.2

3

3

›ip: you can derive your value converter from 4


+   and return its own instance
in the ," B  override. So you can use it directly without referencing it from the
resources.

ëÊ
 !
21 2 
  (

 )*
"
What is a CollectionView?

Navigation

Filtering

Sorting

Grouping

How to create a CollectionView in XAML

)
 
/   0

WPF has a powerful data binding infrastructure. It allows you to bind almost any kind of
collection directly to a view. But when it comes to sorting, filtering and grouping the support of
the collections is rare. That's the point where the iollection@iew comes into play. A collection
view is a wrapper around a collection that provides the following additional features:

è‘ Navigation
è‘ Sorting
è‘ Filtering
è‘ Grouping

ë/

 —
/   

The following example shows you how to create a collection view and bind it to a ListBox

m"#
 <    # 566=     

  < <    # 566=   

m8    / "'  3

m"#

½

 ' B #

/

½
' B #(.

/

>'  ' B #4" (.2

3

3

""
½

 ' B #4" 

/

½ ' B #&  B #2 



½
' B #'  

/

 /  &  B #2 3

3

½
' B #4" (.

/

8m'   A ' (.2

&  B #' B #  A >  B # (  .2

3

3

Ê
 !
 

The collection view adds support for selection tracking. If you set the property
!  "'   to  on the view that the collection is bound to, it
automatically synchronizes the current item of the CollectionView and the View.

m8    / "' 3 


!  "'    

If you are using a MVVM (Model-View-ViewModel) pattern, you don't have to extra wire-up the
  "  of the control, because it's implicity available over the CollectionView.

8m'   A ' (.2

' B #&  B # 


' B #  A >  B #(  .2

&  B # ' ' " '  ' "2 

½ '  ' " ( 


 " )+, - .

/

*     "  

3
"$
You can also manually control the selection from the ViewModel by calling the
4, ' 0(. or 4, ' 8(. methods on the CollectionView.

  !

To filter a collection view you can define a callback method that determines if the item should
be part of the view or not. That method should have the following signature: % 
0  (%C  . . Now set the delegate of that method to the 0   property of the
CollectionView and you're done.

' B #&  B # 


' B # A >  B #(  .2

&  B # 0  ' 0  

½ ' 0  ( 


 .

/

'      ' 2

    ; '(&   .2

3

÷ 

If you change the filter criteria and you want to refresh the view, you have to call *  (. on
the collection view

½
  0  

/

 /  &  2 3

 

/

&   ,  2

;!  !' " (0  .2

&  B # *  (.2

3

3

 !

"
Sorting data ascending or descending by one or multiple criterias is a common requirement for
viewing data. The collection view makes it so easy to achieve this goal. Just add as many
>   as you like to the CollectionView

' B #&  B # 


' B #  A >  B #(  .2

&  B # >   -""(

  >  (8; )


8>  - ".2

&  B # >   -""(

  >  (0; )


8>  - ".2


  !

The sorting technique explained above is really simple, but also quite slow for a large amount of
data, because it internally uses reflection. But there is an alternative, more performant way to do
sorting by providing a custom sorter.

8' B # &  B # 


' B #  A >  B #(  .2

  8' B #2 

&  B # ' '  (.2

½

 '   <' 

/

½
' ( 
 ) 
!.

/

'  7  ' 2

'  K! ' 2

   7; ' ( K; .2

3

3

1  !

Grouping is another powerful feature of the CollectionView. You can define as many groups as
you like by adding A>   to the collection view.

"
Êote: „rouping disables virtualization! This can bring huge performance issues on large data
sets. So be careful when using it.

' B #&  B # 


' B #  A >  B #(  .2

&  B # A>   -""( 


 !A>   ('!..2

To make the grouping visible in the view you have to define a special A! on the view.

m8    / "' 3 

m8  A!  

mA!  "     

m>   

 m  
 / " ; 3 

m>   

mA!  "     

m8  A!  

m8  

ë

/    ,á-

It's also possible to create a CollectionView completely in XAML

m"#
 <    # 566=     

  < <    # 566=   

m"#*   

m' B #   / "3 <9 !  B # 

m' B # A>   

m  !A>    !; '!

m' B # A>   

m' B #  

m"#*  

m8    / " / *  


 B #33
"
m"#

á  3 3 á  *

›his article is not yet finished...

  

In conventional user interface programming techniques (as we know it from WinForms) we


usually add event handlers to controls and implement the logic of a view in the code -behind. It
is the most simple and fastest way to get a functional user interface. But this approach has some
disadvantages:

è‘ Presentation and logic are tightly coupled


è‘ Replacing a control on the view often requires code changes
è‘ You cannot have more than one view sharing the same logic
è‘ To test the user interface logic you need to do comple x UI testing.

  !á  3 3 á  




WPF brings up a very flexible and powerful databinding framework and this favors a new pattern
how to bind presentation and logic together.

The idea of the MVVM pattern is the following:

è‘ A model that contains the data


è‘ A passive view-model that collects and prepares the data so that is can easy be
consumed by the view.
è‘ And a view that is defined in XAML and should not have any logic in the code -behind. It
binds to the view-model by only using data binding.

"
Model-View-ViewModel Example

Model

ViewModel

View

(



  )*
What we want to do is a simple entry form for an e-mail address. If the user enters an invalid e-
mail address, the border of the textbox gets red and the tooltip is showin g the reason.

    !


 ÷ 4.Ê'." 5

$
In this example I am implementing an generic validation rule that takes a regular expression as
validation rule. If the expression matches the data is treated as valid.

m!

B "       

m!

½

 *  B "*  <B "* 

/

½   & 2

½ *  &  2

½
    

/

 /  & 23

 

/

& ,  2

&   *  (& )*    ' .2

3

3

½
*  B "* (.

/

3

½
 B "*  B " ( 
,  )'  
  .

/

(,  LL1&  4 (,  (.. .

/

   B "*   ( ) ,  


, " ? "" .2

3
$c
 

/

   B "*   ( ).2

3

3

3

First thing I need to do is place a regular expression pattern as string to the windows resources

m"#*   

m!< <9 !  *  MN?-?OPNQ#Q?PEN?-?O6?JPR

N?-?O6?JPNQ#Q?PEN?-?O6?JPQN?-?OPN?-?OQP

EN?-?OPSm!<

m"#*   

 


 
  3  !

The following converter combines a list of B "+ into a string. This makes the
binding much easier. In many samples on the web you see the following binding expression:

/ " * ,  /* ,  


 3) (B "+.N6P+' 3

This expression works if there is one validation error. But if you don't have any validation errors
the data binding fails. This slows down your application and causes the following message in
your debug window:

! "#>+<$=<' T NPT,  (! 


TB "+U.T( B "+.U(! 
T* " !% ,% ' V$W.
"+  < (6.N6P+' 2> U   U

The converter is both, a value converter and a markup extension. This allows you to create and
use it at the same time.


NB  ', (½(* " !% ,% '  mB "+ .)
½(  ..P

½

 B "+',   <4
+  )
B  ',  

/

$
½
  
 ," B  ( , ," 
 , ," .

/

   B "+ ',   (.2

3



½
 
', ( 
,  )!  ! )  

  )

'     .

/

* " !% ,% '  mB "+ 

,   * " !% ,% '  mB "+2 



( .

/

    +!2

3

    X()(  

   +'  


 .-!(..2

3

½
 
',  
( 
,  )!  ! )  

  )

'     .

/

   ;   "+  (.2

3

3

/

' 
'

$
Next thing is to create an error template for the text box.

m'     <9 !   +     ! ' 

mA"'  "0  

m  -   *B   -   

"$= $=46)?F)?F)6

 / *  + 3 

 / "+  ; " "+  ) 

 -" "+  (B "+.) 

',  /
<B "+ ',  33 

m "  "  * " " 


  $4?$

m-" "+     "  ; " "+   

m " 

mA"

m'     

'

 ÷ 
 ' 
  

Finally we can add the validation rule to our binding expression that binds the   property of
a textbox to a EMail property of our business object.

m    <;  +4    / *  


   +   3

m    

m " +4 "      !' " 

m "B "*  

 m   <*  B "*   / *  


 *  3

m "B "*  

m "

m     

m   

ë

"


 
$"
If you want to force a data validation you can manually call "  (. on the binding
expression. A useful scenario could be to validate on 80 (. even when the value is
empty or to initially mark all required fields. In this case you cann call 0 B "(. in
the 8" " event of the window. That is the time, when the databinding is established.

The following code shows how to get the binding expression from a property of a control.

½ 0 B " (.

/

 ; A  "+   (      ! ."  (.2

3


/

  

If you want to databind two properties that have incompatible types, you need a piece of code
in between, that converts the value from source to target type and back. This piece of code is
called ValueConverter. A value converter is a class, that implements the simple interface
B  ',   with the two methods %C ', (%C ,  . and %C 
',  
(%C ,  . .

ë   

/

WPF already provides a few value converts, but you will soon need to implement your own
converts. To do this, add a class to your project and call it
N ! PN ! P',   . This is a common naming for value converters.
Make it %  and implement the B  ',   interface. That's all you need to do.

½

   B% !' ,  <B  ',  

/

½
 
', ( 
,  )!  ! ) 

 
  )'     .

$$
/

>  , % ,% ! 

3

½
 
',  
( 
,  )!  ! ) 

 
  )'     .

/

>  , ,% !% 

3

3

ë 

/ ,á-

First thing you need to do is to map the namespace of your converter to a XAML namespace.
Then you can create an instance of a value converter in the resources of the view and give it a
name. Then you can reference it by using / *  3 

m"# <' B ' > "#$ 



  <  ?  <B ' >  



m"#*   

m <  B% !',   <9 ! ,  

m"#*   

mA"

m B% !/ "0 ) 

',  / *   ,  33 

mA"

m"#

 " 
!
/

If you want to use a normal ValueConverter in XAML, you have to add an instance of it to the
resources and reference it by using a key. This is cumbersome, because and the key is typically
just the name of the converter.

$
A simple and cool trick is to derive value converters from 4
+   . This way you can
create and use it in the binding like this:  / "  )
',  / <4!',  33, and that is quite cool!

½
% 
   ',   <4
+  

/

½
  
 ," B  ( , ," 
 , ," .

/

  2

3

3

 !
/

The StringFormatConverter is a useful converter to control the format of an implicit string


conversion of an object (e.g. if you bind a DateTime to a TextBlock ).

NB  ',  (½( 


.)½(  ..P

½

 0',   <  ',  )B  ',   

/

½
 
', ( 
,  )!  ! )  

  )

 ! A % '     .

/

     2

(1  ; +!(..

/ 

    0(   )),  .2

3

 

/ 

  ,  (.2

3
$
½
 
',  
( 
,  )!  ! )  

  )

 ! A % '     .

/

   2

3

3


 

A simple Border can be dragged by mouse - because of an attached drag behavior.

  

Behaviors are a new concept, introduced with Expression Blend in Version 3, to encapsulate
pieces of functionality into a reusable component. These components than can be attached
to controls to give them an additional behavior.

The ideas behind behaviors are to give the interaction designer more flexibility to design
complex user interactions without writing any code.

Example of a behaviors are drag&drop, input validation, pan and zoom, re -position of elements,
etc... The list of possible behaviors is very long.

Imaging an application that has a list of customers and the user can add some of them to
subscriber lists. This interaction can be designed by providing an "Add" button next to each
subscriber list. But if the interaction designer wants to add drag&drop functionality, he needs to
discuss it with the developer and wait until the implementation is done. With behaviors he just
drags a drag and drop behavior on each list and we are done.

ë $
     

$
Using behaviors in Expression Blend is as simple as adding an element to the design surface. In
the asset library you find a new secion called "Behaviors". It lists all behaviors available within
your project. Just grab one of these and drag it onto the element you want to add this behavior
and thats it.

The behavior appears as an child element in the visual tree. By clicking on it you can configure
the properties of the behavior.

ë  

To add behaviors to an element you need some kind of an extension point. This is an attached
property called    , .

This attached property holds the list of behaviors for that element and pass a reference to the
element into the behavior. The behavior than can register itself to events and property changes
and so extend the functionality of the element.

$
The idea is simple, but very clever. They don't need any new infrastructure, they just reuse the
existing one.

m "  
"8  

 m <   , 

  m%<> , 

 m <   , 

 m  
 > "1 

m " 

ë   " $


 

The following example shows the implementation of the drag behavior we used above. Just
derive from ,m22 and override the -  "(. method.

½

 > , < ,m+  

/

½     2 

½    2 

½        (.2

½ 
 -  "(.

/

"# -  ' 4"#2

-  "%C  * " 2

-  "%C  4 8  ># Y( " ) .

/

    -  "%C    ( 


(.) .2

    A  ( .2

-  "%C  ' 4 (.2

32

-  "%C  4 8  Y( " ) .

/


-  "%C  *  4 ' (.2

32

-  "%C  4 4, Y( " ) .

/

B " A  ( .?  2 

(-  "%C  4 ' ".

/

  7"72

  K"K2

3

32

3

3

-  
$
 

Since its so cool and easy to create your own pice of interactivity, I am sure that we will find
hunderts of behaviors available soon. I tried to make a list of some popular ones.

è‘ Xoom Behavior
è‘ Glass Behavior
è‘ Shake Behavior
è‘ Transparency Behavior

c
Day 5 - Templates and Styles

— ( !*


— $ 
&" 


In the past, we focused mainly on building products that fulfilled the functional requirements of
the user. User experience was often considered late in the development process. But today the
customer demands more than just a working product. Providing the right features is still the
prerequisite for a good product, but to turn it into something extraordinary you need to provide
a good user experience!

Providing a rich user experience is not a thing of fortune. It needs to be planed, designed and
integrated into the development of a product. Designing a rich user experience is not only
about make up your user interface by some graphics and gradients - its a much broader
concept. Its about creating an emotional connection between the user and your software. It
makes the user feel good and so he likes to continue using the software.

Ê' ( !

Microsoft recognized, give development teams the power to create rich user experiences it
needs a lot more graphical tool support than VisualStudio can provide today. So they decided to
create a new tool suite - made for designers.

This tool suite is called áicrosoft Expression. It consists of the four products:

è‘ Expression Blend is built to create user interfaces in WPF and Silverlight. It builds the
bridge between designer and developers. It can open VisualStudio solutions


è‘ Expression Design is a leightweight version of Adobe Illustrator to create and edit
vector graphics.
è‘ Expression áedia is built to encode, cut and enrich video files and optimize them for
silverlight streaming
è‘ Expression Web is Microsoft next generation of HTML and Javascript editor. Its the
replacement for Frontpage.

Together they are a powerful package. The following illustration shows a sample workflow of
integrating a vector image that is created by a graphics designer in Adobe Illustrator into a WPF
project that is part of a VisualStudio solution.

(  ) 


)**+

Developing a WPF application with a rich user experience requires a lot more skills than just a
requirements analyst that defines a list of use cases and developer that implements the
software. You have to find out what the user really needs. This can be done by following a us er
centered approach.


.  ÷6  

Like in any kind of software projects its important to know and focus the target of your
development. You should talk to stakeholders and users to find out the real needs. These needs
should be refined to features and expressed in use cases (abstract) or user scenarios
(illustrative). Priorize the tasks by risk and importance and work iteratively. This work is done by
the role of the requirements engineer.

./

 

—*"

Creating a user interface prototype is an important step to share ideas between users and
engineers to create a common understanding of the interaction design. This task is typically
done by an interaction designer. It's helpful to only sketch the user interface in a rou gh way to
prevent early discussions about design details. There are multiple techniques and tools to do
this. Some of them are:

è‘ Paper prototype
Use paper and pencil to draw rough sketches of your user interface. No tools and
infrastructure is needed. Everyone can just scribble thier ideas on the paper.
è‘ Wireframes
Wireframes are often used to sketch the layout of a page. It's called wireframes because
you just draw the outlines of controls and images. This can be done with tools like
PowerPoint or Visio
è‘ Expression Blend 3 - Sketch Flow Sketch flow is a new cool feature to create interactive
prototypes directly in WPF. You can use the integrated "wiggly style" to make it look

"
sketchy. The prototype can be run in a standalone player that has an integrated feedback
mechanism.
è‘ Interactive Prototype The most expensive and real approach is to create an (reusable)
interactive prototype that works as the real application but with dummy data.

It is strongly recommended to test your UI prototype on real users. This helps you to find out
and address design problems early in the development process. The following techniques are
very popular to evaluate UI prototypes:

è‘ Walktrough
A walktrough is usually done early in a project with wireframes or paper prototypes. The
user gets a task to solve and he controlls the prototype by touching on the paper. The
test leader than presents a new paper showing the state after the interaction.
è‘ —sability Lab
To do a usability lab, you need a computer with a screen capture software and a camera.
The proband gets an task to do and the requirements and interaction engineer watch
him doing this. They should not talk to him to find out where he gets stuck and why.

.     -! 


 ÷
—

7.!
1
 
( !
8.'

÷ 

Buliding a modern user interface with a rich user experience requires additional skills from your
development team. These skills are described as roles that can be distributed among peoples in
your development team.

è‘ Developer
The developer is responsible to implement the functionality of the application. He
creates the data model, implements the business logic and wires all up to a simple view.
è‘ „raphical Designer
The graphical designer is responsible to create a graphical concept and build graphical
assets like icons,logos, 3D models or color schemes. If the graphical designer is familiar
with Microsoft Expression tools he directly creates styles and control templates.
è‘ Interaction Designer
The interaction designer is responsible for the content and the flow of a user interface.
He creates wireframes or UI sketches to share its ideas with the team or customer. He
should validate his work by doing walktroughs or storyboards.
è‘ Integrator
The integrator is the artist between the designer and the developer world. He takes the
assets of the graphical designer and integrates them into the raw user interface of the

$
developer. This role needs a rare set of skills and so it's often hard to find the right
person for it.

á

The New Iteration - Microsoft Paper about the Designer/Developer collaboration

   "  )*


,*/1052*+1,

Imagine you want to create an application with a unique design. All your buttons should have an
orange background and an italic font. Doing this the conventional way means that you have to
set the 
" and the 0! property on every single button.

m
   B   -   

m  
" 0!   

 ""F)Z4Z! m 

m  
" 0!   

 ""F)Z4Z m 

m  
" 0!   

 ""F)Z4Z  m 

m
 

This code is neither maintainable nor short and clear. The solution for this problem are styles.

The concept of styles let you remove all properties values from the individual user interface
elements and combine them into a style. A style consists of a list of setters. If you apply this style
to an element it sets all properties with the specified values. The idea is quite similar to
Cascading Styles Sheets (CSS) that we know from web development.

To make the style accessible to your controls you need to add it to the resources. Any control in
WPF have a list of resources that is inherited to all controls beneath the visual tree. That's the
reason why we need to specify a <9 !!!  property that defines a unique resource
identifier.

To apply the style to a control we set the ! property to our style. To get it from the
resources we use the / *  N  9 !P3 markup extension.

m"#

m"#*   

m!  <9 !!!  !  

m    ! 


"B   

m    !0! B    

m    ! ""B  F)Z

m    !4B  Z

m! 

m"#*   



m
   B   -   

m ! / *  !! 3 ! m 

m ! / *  !! 3  m 

m ! / *  !! 3   m 

m
 

m"#

What we have achieved now is

è‘ A maintainable code base


è‘ Removed the redundancy
è‘ Change the appearance of a set of controls from a single point
è‘ Possibility to swap the styles at runtime.

"   


A style in WPF can base on another style. This allows you to specify a base style that sets
common properties and derive from it for specialized controls.

m!  <9 !% ! 

m    !0 B  $5

m    ! 


"B   

m! 

m!  <9 !% "!   "/ *  % ! 3 

m    !0 B    "



m! 

/ ' 

  

Controls in WPF are separated into logic, that defines the states, events and properties and
template, that defines the visual appearance of the control. The wireup between the logic and
the template is done by DataBinding.

Each control has a default template. This gives the control a basic appearance. The default
template is typically shipped together with the control and available for all common windows
themes. It is by convention wrapped into a style, that is identified by value of the
>  ! 9 ! property that every control has.

The template is defined by a dependency property called    . By setting this property to


another instance of a control template, you can completely replace the appearance (visual tree)
of a control.

The control template is often included in a style that contains other property settings. The
following code sample shows a simple control template for a button with an ellipse shape.

m!  <9 !>  !   !  

m    !   

m  B  

m'      ! / <!  3 



 mA"

 m+  0 /   " 


"3 

 
/   " "  3 

 m'       -   '  

 B   -   '  

 mA"

m'     

m  B  

m  

m! 

m ! / *  >  ! 3 

A Button without and with a custom control template

/*

When you create a custom control template and you want to define a placeholder that renders
the content, you can use the '      . By default it adds the content of the
'  property to the visual tree of the template. To display the content of another property
you can set the '      !! 
 


Triggers

{RelativeSource TemplatedParent} not working in DataTriggers of a ControlTemplate


If you want to bind to a property of a property on your control like >8" " you
cannot use a normal Trigger, since it does not support this notation, you have to use a
DataTrigger.

But when you are using a DataTrigger, with /* ,     "  3 it will
not work. The reason is, that ›½  can only be used within the
iontrol›emplate. It is not working in the Trigger section. You have to use the
/* ,   3 " 

)
 
  ! !
  
    !
  


There is something you need to know when setting a value of an element within a control
template: The value does have a lower precendence as the local value! So if you are setting the
local value in the constructor of the contained element, you cannot override it within the
controltemplate. But if you use the element directly in your view, it will work. So be aware of this
behavior!.

Here you can find more information about DependencyProperty value precendence:
Dependency Property Value Precedence

(

' 

  

Data Template are a similar concept as Control Templates. They give you a very flexible and
powerful solution to replace the visual appearance of a data item in a control like ListBox,
ComboBox or ListView. In my opinion this is one of the key success factory of WPF.

If you don't specify a data template, WPF takes the default template that is just a TextBlock. If
you bind complex objects to the control, i t just calls (. on it. Within a DataTemplate,
the DataContext is set the data object. So you can easily bind against the data context to display
various members of your data object

(

' 
  9 !
  *"1 

Whereas it was really hard to display complex data in a ListBox with WinForms, its super easy
with WPF. The following example shows a ListBox with a list of DependencyPropertyInfo
instances bound to it. Without a DataTemplate you just see the result of cal ling (. on
the object. With the data template we see the name of the property and a TextBox that even
allows us to edit the value.


m1??>    ??

m8    / "3



m1??>    ??

m8    / "3 "   

A" "    

 ' -     

m8       

m>   

mA"4Z

 mA"' >  

 m' >  "-


 " A9 !

 m' >  "E

 mA"' >  

 m  
 / "; 3 0   "

 m   A" ' $ / "B  3 

mA"

m>   

m8       

c
m8  

ë 
(

' 
   ' 
  !



Our property grid looks nice so far, but it would be much more usable if we could switch the
editor depending on the type of the property.

The simplest way to do this is to use a >     . The DataTemplateSelector


has a single method to override:     (%C   )>  "  !%C 
 .. In this method we decide on the provided   which DataTemplate to choose.

The following exmple shows an DataTemplateSelector that decides between tree data
templates:

½

   !>     <>    

/

½
>   >  >    / 2 23

½
>     >    / 2 23

½
>   +>    / 2 23



½
 >       ( 
 )

>  "  !%C    .

/

>  "  !  !"   >  "  !  !2 

("  !! ½(..

/

    >   2 

3

("  !! +.

/

  +>   2 

3

  >  >   2 

3


3

m"# <' >   "#$ 

  <     # 566=     

  < <    # 566=   

  <  ?  <>    

  <! ?  <! 2 % !  % 



m"#*   

m1??>  >    ??

m>    <9 !>  >    



m>   

m1??>      ??

m>    <9 !  >    



m>   

m1??>   + ??

m>    <9 !+>    



m>   

m1??>     ??

m <  !>     <9 !     

 >  >   / *  


>  >   3 

  >   / *  


 >   3 

 +>   / *  +>   3 

m"#*   


mA"

m8    / "3A" "    

  ' -     

       / *  


    3 

mA"

m"#

ë
    (

' 


If you want to change the appearance of a ListBoxItem when it is selected, you have to bind the
IsSelected property of the ListBoxItem. But this is a bit tricky, you have to use a relative source
with FindAcestor to navigate up the visual tree until you reach the ListBoxItem.

m>    <9 !>  >    

m "  <; %"  :6



m " 

m>     

m>  "/ "* ,   

/* ,  4" 0"- )- !  

/ <! 8   33)   "3 B   

m   ; %"   ! B  $66

m> 

m>     

m>   

"
Ôocalization
ëow to evaluate a localization mechanism
To choose an appropriate localization mechanism you have to find one that meets the
requirements and your companys established translation process.

Criterias to compare the localization mechanisms among each others:

è‘ ‘ ‘
 ‘
è‘ —
 ‘‘‘‘ ‘
è‘ › 
‘‘ ‘

‘
è‘ |
‘‘  ‘‘
‘
è‘ ›
 ‘  ‘

Different WPF translation mechanisms compared 

è‘  ‘
‘‘| 

è‘  ‘
‘  ‘



Ôocalization of a WPF application using a custom


MarkupExtension

' 

$
A simple and effective way to localize application resources is to write a custom
4
+   that provides a localized value. The extension takes a parameter in the
constructor that is the unique resource key. When the DepdendencyProperty asks for the value,
the markup extension looks up the value from a generic resource provider. This gives you the
flexibility to reuse the resource management and translation process that is already established
within your company.

Using a custom markup extension has some advantages

è‘   ‘‘  ‘


 ‘
è‘ ‘ ‘
 ‘ ‘  ‘
è‘ 
‘  ‘ ‘‘‘
 ‘ 

   
 
The idea of using a markup extension for localization is not unique by me. There are also other
similar implementations out there. Here you find some links:

è‘  | 
‘ ‘ 

è‘ ÷
‘| 
‘ ‘  ‘!
 

ë  
The usage of the markup extension is very simple. Just replace the string you want to localize by
/ <    9 !3 .

‘‘

‘  ‘ 
 ‘ ‘‘

‘‘

‘‘

   
  


  
   
The translation infrastructure consists of the folling parts

è‘ ›  

The translation manager is a static class that manages the current language and notifies
all markup extensions, to update their values when the language changes. It also
provides access to translated resources. The resources itself are provided by a generic
translation provider.

è‘ ›      
The tanslate markup extension knows the resource key and provides the translated
value. It listens to the LanguageChanged event of the translation manager and updates
its value. This event handler is implemented by the weak event pattern to prevent
memory leaks.

è‘ ›  
The translation provider is a class that provides the translated resources. It has to
implement the  and can access any kind of resources you like.
For e.g. ResX, XML or text files.

‘‘

½ ‘‘‘ ‘  ! ‘

‘‘‘‘½
‘  ‘" #$‘

‘‘

‘‘‘‘½ ‘ %  ‘ #&‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘" #‘
‘ #$‘

‘‘‘‘‘

‘‘

‘‘‘‘'() % # &*‘

‘‘‘‘½ ‘  ‘+#‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘)‘ ‘
 ‘" #$‘‘

‘‘‘‘‘‘‘‘‘ ‘" #‘


‘$‘

‘‘‘‘‘

‘‘

‘‘‘‘½ ‘ 

‘ 
 ‘, % ‘ &‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘-)‘
‘
‘)% , &‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ ‘
‘
‘. %" #&‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘ $‘

‘‘‘‘‘‘‘‘
 ‘-), % &$‘


‘‘‘‘‘

‘‘

‘‘

‘‘

½ ‘‘.‘ ‘ /0‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 1#!#2)0‘.!- ‘

‘‘‘‘½
‘  ‘" #$‘

‘‘

‘‘‘‘½ ‘. %‘  ‘ #&‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘" #‘
‘ #$‘

‘‘‘‘‘‘‘‘/))2) ) (/ %‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘  ) 0‘ &$‘

‘‘‘‘‘

‘‘

‘‘‘‘3. %&‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘.!%
&$‘‘

‘‘‘‘‘

‘‘

‘‘

‘‘‘‘½ ‘ ‘.!%&‘‘

‘‘‘‘ ‘‘

‘‘‘‘‘‘‘‘.!% 
&$‘‘

‘‘‘‘‘‘‘‘4 !!5 % &$‘‘

‘‘‘‘‘‘

‘‘

‘‘‘‘½

‘ ‘ ‘.!% ‘!)&‘‘

‘‘‘‘ ‘‘

‘‘‘‘‘‘‘‘‘%!)&‘‘

‘‘‘‘‘‘‘‘ ‘‘

‘‘‘‘‘‘‘‘‘‘ /))2) ) 6/%‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘  ) 0‘ &$‘‘

‘‘‘‘‘‘‘‘‘‘

‘‘‘‘‘‘

‘‘

‘‘

‘‘‘‘½ ‘ 
 ‘,‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘)‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ 
 ‘ )  %" #&$‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘

‘‘

‘‘‘‘½ ‘ ‘6  %#!‘)#!0‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 
 ‘0‘()‘ &‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘%)#!‘

‘ ½
%/))2) ) &&‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ 7/))2) %0‘&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ 
 ‘$‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘‘‘‘
 ‘1$‘

‘‘‘‘‘

‘‘

‘‘‘‘½
‘ ‘7/))2) % 
 ‘0‘()‘ &‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘%‘!#2)‘ 8
‘ ‘&‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ !#2) %‘ 0‘


‘!#2)() % , &&$‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘

‘‘

‘‘‘‘½ ‘

‘!#2)9‘!#2)$ ‘

‘‘

‘‘

‘‘

½ ‘‘ ) ‘

‘‘‘‘½
‘  ‘  )‘" )$ ‘

‘‘

‘‘‘‘½ ‘

‘9‘/))2)$ ‘

‘‘

‘‘‘‘½ ‘1‘/)) ‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘)‘ ‘
 ‘22 : $‘‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘ %‘‘8
‘22 : &‘

‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 22 : ‘
‘$‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 7/))2) %&$‘

‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘

‘‘

‘‘‘½ ‘- 1 ‘/)) ‘

‘‘‘ ‘

‘‘‘‘‘‘‘)‘

‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘ %‘‘ 8
‘ &‘

‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 
 ‘ /))$‘

‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘ 
 ‘- !# 1 %&$‘

‘‘‘‘‘‘‘‘

‘‘‘‘‘

‘‘

‘‘‘‘½ ‘  ‘ )‘ ‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘)‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘%" )‘

‘ &‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ " )‘


‘
‘ ) %&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ 
 ‘" )$ ‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘

‘‘
c
‘‘‘‘½ ‘‘‘ ‘)$‘$‘ ‘

‘‘

‘‘‘½
‘ ‘7/))2) %&‘

‘‘‘ ‘

‘‘‘‘‘‘‘‘‘%/))2)‘ 8
‘ &‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ /))2) % 0‘() !#&$‘

‘‘‘‘‘‘‘‘

‘‘‘‘‘

‘‘

‘‘‘½ ‘ 
 ‘ %  ‘ #&‘

‘‘‘ ‘

‘‘‘‘‘‘‘%‘ 8
‘ &‘

‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ 
 ‘,‘
 % #&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ %‘,‘ 8
‘ &‘

‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 
 ‘,$ ‘

‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘‘‘
 ‘  % 8 ;8 0‘ #&$‘

‘‘‘‘‘

‘‘

‘‘


nteraction
Oehaviors

A simple Border can be dragged by mouse - because of an attached drag behavior.

  
Behaviors are a new concept, introduced with Expression Blend in Version 3, to encapsulate
pieces of functionality into a reusable component. These components than can be attached
to controls to give them an additional behavior.

The ideas behind behaviors are to give the interaction designer more flexibility to design
complex user interactions without writing any code.

Example of a behaviors are drag&drop, input validation, pan and zoom, re -position of elements,
etc... The list of possible behaviors is very long.

Imaging an application that has a list of customers and the user can add some of the m to
subscriber lists. This interaction can be designed by providing an "Add" button next to each
subscriber list. But if the interaction designer wants to add drag&drop functionality, he needs to
discuss it with the developer and wait until the implementa tion is done. With behaviors he just
drags a drag and drop behavior on each list and we are done.

ë $
      
Using behaviors in Expression Blend is as simple as adding an element to the design surface. In
the asset library you find a new secion called "Behaviors". It lists all behaviors available within
your project. Just grab one of these and drag it onto the element you want to add this behavior
and thats it.

The behavior appears as an child element in the visual tree. By clicking on it you can configure
the properties of the behavior.


‘
‘

ë  


To add behaviors to an element you need some kind of an extension point. This is an attached
property called    , .
This attached property holds the list of behaviors for that element and pass a reference to the
element into the behavior. The behavior than can register itself to events and property changes
and so extend the functionality of the element.

The idea is simple, but very clever. They don't need any new infrastructure, they just reuse the
existing one.

‘‘

‘ )
/)2 ‘‘

‘  2 ‘

‘ ‘ - .)2 ‘

‘  2 ‘

"
‘  ‘ 
.)‘‘8 ‘‘

‘

‘‘

‘‘

ë   " $


  
The following example shows the implementation of the drag behavior we used above. Just
derive from ,m22 and override the -  "(. method.

‘‘

½ ‘‘.)2‘ ‘2 : ‘

‘‘‘‘½
‘‘ $ ‘

‘‘‘‘½
‘‘ $ ‘

‘‘‘‘½
‘1‘1‘
‘
‘1 %&$‘

‘‘

‘‘‘‘½

‘ 

‘ ‘7(2 %&‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘<‘!‘
‘(!!  < $‘

‘‘‘‘‘‘‘‘(7-= 61 ‘
‘1$ ‘

‘‘

‘‘‘‘‘‘‘‘(7-= /1.< ‘>


‘%0‘ &‘
‘‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘  ‘


‘(7-=  %‘

%&0‘!‘ &$‘

‘‘‘‘‘‘‘‘‘‘‘‘  ‘


‘4 %!&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ (7-= !  %&$‘

‘‘‘‘‘‘‘‘$‘

‘‘

‘‘‘‘‘‘‘‘(7-= /1:! ‘>


‘%0‘&‘

‘‘‘‘‘‘‘‘ ‘
$
‘‘‘‘‘‘‘‘‘‘‘‘ (7-= 6 ! %&$‘

‘‘‘‘‘‘‘‘$‘

‘‘

‘‘‘‘‘‘‘‘(7-=   ‘>


‘%0‘ &‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ ,‘11‘
‘4 %‘!‘&‘?‘ $ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘%(7-=  ! &‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 1 @‘
‘11@$‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 1 A‘
‘11A$‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘$‘

‘‘‘‘‘

‘‘

‘‘

-  
$
  
Since its so cool and easy to create your own pice of interactivity, I am sure th at we will find
hunderts of behaviors available soon. I tried to make a list of some popular ones.

è‘ X‘" 
è‘ 

‘" 
è‘  ‘" 
è‘ ›
  ‘" 

Drag and Drop in WPF

,*/1052*+1,

Drag&Drop can drasticly improve the productiviy and user experience of a software. But only a
few programmers provide drag and drop functionality in their applications, because they think


its much more dificult than it really is. This article shows how simple drag and drop can be
implemented in WPF.

(
!:( ; 

1.‘ Detect a drag as a combinatination of á  á and á    


2.‘ Find the data you want to drag and create a   that contains the format, the
data and the allowed effects.
3.‘ Initiate the dragging by calling  
 
4.‘ Set the ?  property to › on the elements you want to allow dropping.
5.‘ Register a handler to the  
 event to detect a dragging over the drop location.
Check the format and the data by calling     on the event args. If the data
can be dropped, set the   property on the event args to display the appropriate
mouse cursor.
6.‘ When the user releases the mouse button the  
  event is called. Get the data by
calling the   method on the  object provided in the event args.

...and that's all the magic.

(
!
To start the drag operation, we have to detect a mouse move while the left mouse button is
pressed. To do this we have to hook up handlers on the  , #4 4, and
 , #4 8  ># events.

To prevent occasionally drags, its a good design to not start the drag operation until the user
has moved the mouse cursor by a couple of pixels. WPF provides a con stant that contains the
amount of pixel that Windows uses.

When the drag is initiated, we need to specify the data we want to drag. In our case its the data
of the 8B #  we dragged. We find the 8B #  in the   of
the mouse event args. By calling  ' A   0'  we get
the data behind the 8B # .

Create a >%C  to transport the data to the drop location. The constructor takes two
arguments. A string that describes the format and the data we want to drag.

/,<‘  
.)/ ‘‘

‘‘‘‘‘‘‘‘‘‘ < /1.<


/"< /1.< ‘‘

‘‘‘‘‘‘‘‘‘‘ <  


/"   ‘

‘‘

‘‘


½
‘ ‘/"< /1.< % 
 ‘0‘
 ()‘&‘

‘‘‘‘‘ ‘2‘‘! ‘

‘‘‘‘‘
‘4 % &$‘

‘‘

‘‘

‘‘

½
‘ ‘/"   % 
 ‘0‘ ()‘ &‘

‘‘‘‘‘4‘2‘‘‘! ‘

‘‘‘‘‘‘
‘4 % &$‘

‘‘‘‘,‘11‘
‘‘ ?‘$ ‘

‘‘

‘‘‘‘‘%/1 ‘

‘   ‘BB‘

‘‘‘‘‘‘‘‘ 2(-%11@&‘‘ # 95.). ‘BB‘

‘‘‘‘‘‘‘‘ 2(-%11A&‘‘ # ,.). ‘&‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘4‘2‘ ))‘/,< ‘

‘‘‘‘‘‘‘‘/,<‘,<‘
‘‘‘/,<$‘

‘‘‘‘‘‘‘‘/,<‘,<‘
‘‘

‘‘‘‘‘‘‘‘‘‘‘‘ (2 /,< %%.!#7-= &7)  &$‘

‘‘

‘‘‘‘‘‘‘‘‘‘2‘‘-2‘2‘/,< ‘

‘‘‘‘‘‘‘‘‘‘
‘%&,< 4 ‘

‘‘‘‘‘‘‘‘‘‘‘‘  %,< &$‘

‘‘


‘‘‘‘‘‘‘‘‘5‘2‘)‘B‘!‘! ‘

‘‘‘‘‘‘‘‘.7-=‘).‘
‘
‘.7-= % # 0‘‘ &$‘

‘‘‘‘‘‘‘‘.).!..).! %,<0‘).0‘.).!11 &$‘

‘‘‘‘‘‘

‘‘

‘‘

‘‘

‘9!‘‘2‘!‘2‘, ‘

½
‘  ‘‘(2 %.!#7-=‘ &‘

‘‘‘‘<2‘‘ ‘.!#7-= ‘

‘‘‘‘ ‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘%‘‘‘‘&‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ 
 ‘%&$‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘‘‘‘‘
‘,9! 4 %&$‘

‘‘‘‘‘

‘‘‘‘
‘%‘8
‘ &$‘

‘‘‘‘
 ‘$‘

‘‘

‘‘

(
To make an element be a drop location, set the AllowDrop property to true. When the user
drags an item over the element, the DragEnter event is called. In this event you can analyze the
data and decide if a drop is allowed or not.

When the user releases the mouse button the Drop event is called. The data is available in the
DataObject provided in the DragEventArgs.

/,<‘  
.!/ ‘‘

‘‘‘‘‘‘‘‘‘‘ .!
.!/".! ‘‘

‘‘‘‘‘‘‘‘‘‘ .)
.!/".) ‘‘

‘‘‘‘‘‘‘‘‘‘ (<.!
 ‘‘

‘‘

‘‘

½
‘ ‘/".) % 
 ‘0‘.)()‘ &‘

‘‘‘‘‘%8.4. %  &‘CC‘

‘‘‘‘‘‘‘‘‘

‘ &‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘11‘
‘.).!11 $‘

‘‘‘‘‘

‘‘

‘‘

‘‘

½
‘ ‘/".! % 
 ‘0‘.)()‘ &‘

‘‘‘‘‘%.4. % # &&‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘
‘.4.% # &‘‘$‘

‘‘‘‘‘‘‘‘/,<‘,<‘
‘‘‘/,<$‘

‘‘‘‘‘‘‘‘,<(%&$‘

‘‘‘‘‘



‘‘

‘‘

c
÷esource

mprove the performance of merged ÷esourceDictionaries


Each time a control references a *  > ! XAML creates a new instance of it. So
if you have a custom control library with 30 controls in it and each control references a common
dictionary you create 30 identical resource dictionaries!

6.# ). ‘

‘‘‘ 26.#‘

 #/-#$!22 ‘‘‘

6.# ). ‘

‘‘

To get rid of this problem, I created t he  "*  > ! . You can use it the
same way as a conventional ResourceDictionary. The only suptile difference is, that if it is
instanced multiple times, the resources are loaded only once.

‘‘

‘‘

'-# ‘
@.1 % 2! 21<1D;;E! 0‘‘

: &*‘

‘‘

‘ # ‘

‘2‘2‘‘#‘‘‘!5‘‘# ‘

‘2‘‘‘‘#‘‘1‘‘‘‘<2‘2‘‘ ‘

‘‘0‘‘#‘)‘2‘‘1‘2‘2 ‘

‘ # ‘

½ ‘‘ 26.#‘ ‘6.# ‘

‘‘‘‘‘ # ‘

‘‘‘‘‘‘2‘1‘‘‘ ‘

‘‘‘‘‘ # ‘

‘‘‘‘½ ‘  ‘.# :0‘6.# ‘"2.‘


‘

‘‘‘‘‘‘‘‘
‘.# :0‘6.# %&$‘

‘‘

‘‘‘‘‘ # ‘

‘‘‘‘‘/‘-‘1‘2‘‘ ‘

‘‘‘‘‘ # ‘

‘‘‘‘½
‘:‘":$ ‘

‘‘

‘‘‘‘‘ # ‘

‘‘‘‘‘4‘‘‘2‘1‘‘1‘%:6&‘‘‘‘
1‘

‘‘‘‘‘ # ‘

‘‘‘‘½ ‘
‘:‘  ‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘)‘ ‘
 ‘":$‘ ‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ ":‘
‘$‘

‘‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘%8"2. +# %&&‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ ‘1‘2‘#‘‘‘#‘0‘‘‘-#‘) ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ ‘2‘‘1‘2‘- ‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 
 ‘
‘$‘

‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ ‘‘‘‘2‘2 ‘


‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ "2. (%0‘ &$‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘

‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ ‘1‘2‘#‘‘#‘0‘)‘‘1‘ 2‘2‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ ). (%"2. '*&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘

‘‘

‘‘

ëow to read WPF ÷esourceDictionaries from WinForms


When you add resources dictionaries to an WPF project the build action is automatically set to
Page. This means that the compiler generates a BAML stream and adds it to the resources of the
assembly.

Since WPF has the built-in functionality to read a BAML stream but its API is not public, we have
to write a little helper class that access the internal method by using reflection.

‘‘

½ ‘  ‘‘6 ‘

‘‘‘‘½ ‘  ‘ 


 ‘/% ‘ &‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘!‘
‘
‘ %&$‘

‘‘‘‘‘‘‘‘ 21‘ 2‘


‘ ½
%@6 &4 2 % / 0‘‘

‘‘‘‘‘‘‘‘‘‘‘‘ )) - ‘C‘))   &‘

‘‘‘‘‘‘‘‘
 ‘ 2  % 0‘
‘ 
 '*‘ ‘0‘!0‘ 0‘

‘&$‘

"
‘‘‘‘‘

‘‘

‘‘

‘‘

61‘‘
‘ #<(!! 46  %‘

‘‘‘‘
‘:%  #(-#$! #6. 0‘
:+6&&$‘

‘‘‘‘6.#‘‘
‘
%6.# &6 /% &$‘

‘‘

‘‘

$
2D Graphics
Draw lines excactly on physical device pixels
)"  " 

$ "0
When you draw a line in WPF you will experience that they often appear blurry. The reason for
this is the antialiasing system that spreads the line over multiple pixels if it doesn't align with
physical device pixels.

The following example shows a usercontrol that overrides the * "  method for custom
drawing a rectange to the "#'  . Even if all points are integer values and my screen
has a resolution of 96dpi the lines appear blurry. Why?

‘‘

½

‘ 

‘ ‘76%.<)‘<) &‘

‘‘‘‘‘!‘
‘
‘%2 0‘F&$‘

‘‘‘‘6‘‘
‘
‘6%D;0D;0‘G;0‘E;&$‘

‘‘

‘‘‘‘<) .<6) % 0‘!0‘ &$‘

‘‘

‘‘

÷     


WPF is resoultion independent. This means you specify the size of an user interface element in
inches, not in pixels. A logical unit in WPF is 1/96 of an inch. This scale is chosen, because most
screens have a resolution of 96dpi. So in most cases 1 logical unit maches to 1 physical pixel. But
if the screen resolution changes, this rule is no longer valid.

 ! !  
The reason why the lines appear blurry, is that our points are center points of the lines not
edges. With a pen width of 1 the edges are drawn excactly between two pixels.

A first approach is to round each point to an integer value (snap to a logical pixel) an give it an
offset of half the pen width. This ensures, that the edges of the line align with logical pixels. But
this assumes, that logical and physical device pixels are the same. This is only true if the screen
resolution is 96dpi, no scale transform is applied and our origin lay s on a logical pixel.

— ! 
'( *    
All WPF controls provide a property > ,   . If set to true, the control ensures
the all edges are drawn excactly on physical device pixels. But unfortunately this feature is only
available on control level.

— !1      


 ! 
Our first approach to snap all points to logical pixels is easy but it has a lot of assumptions that
must be true to get the expected result. Fortunately the developers of the milcore (MIL stand s
for media integration layer, that's WPFs rendering engine) give us a way to guide the rendering
engine to align a logical coordinate excatly on a physical device pixels. To achieve this, we need
to create a A"   . The A"    contains a list of logical X and Y coordinates
that we want the engine to align them to physical device pixels.
If we look at the implementation of > ,   we see that it does excatly the
same.

‘‘

½

‘ 

‘ ‘76%.<)‘<) &‘

‘‘‘‘‘!‘
‘
‘%2 0‘F&$‘

‘‘‘‘6‘‘
‘
‘6%D;0D;0‘G;0‘E;&$‘

‘‘

‘‘‘‘ 
‘212‘
‘!2 ‘‘D$‘

‘‘

‘‘‘‘‘‘‘)‘ ‘

‘‘‘‘4 ‘)‘
‘
‘4  %&$‘


‘‘‘‘) 4@ (%/1‘>‘212 &$‘

‘‘‘‘) 4@ (%6)2‘>‘212 &$‘

‘‘‘‘) 4A (%!‘>‘212 &$‘

‘‘‘‘) 4A (%‘>‘212 &$‘

‘‘

‘‘‘‘<) 24  %) &$‘

‘‘‘‘<) .<6) % 0‘!0‘ &$‘

‘‘‘‘<) !%&$‘

‘‘

‘‘

The example above is the same as at the beginning of the article. But now we create a
A"   . To the set we add a horizontal or vertical guidelines for each logical
coordinate that we want to have aligned with physical pixels. And that is not the center point,
but the edge of our lines. Therefore we add half the penwidth to each point.
Before we draw the rectange on the >#'  we push the guidelines to the stack. The
result are lines that perfecly match to our physical device pixels

 +    
The last thing we need to consider is that the width of the pen is still defined in logical units. If
we want to keep the pen width to one pixel (think a moment if you really want to have this) you
can scale the pen width with the ration between your screen resolution and WPF's logical units
which is 1/96. The following sample shows you how to do this.

‘‘
‘  , % &‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ !) 1. $‘

 
‘!‘
‘F FF$‘

‘‘


‘‘
‘
‘%‘2 0‘F‘H‘!‘ &$‘

‘‘

‘‘

ëow to get a Oitmap from a Visual


‘‘

½ ‘ ‘ )%,‘0‘  ‘<20‘ ‘2)20‘  ‘12&‘

‘‘‘‘6)!‘-!‘
‘
‘6)! %<20‘2)20‘ IE0‘IE0‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘  -)JD&$‘

‘‘‘‘-!6%&$‘

‘‘

‘‘‘‘)!‘)‘
‘
‘)! %&$‘

‘‘‘‘)(%! %-!&&$‘

‘‘‘‘  ‘% ‘1‘
‘%12&&‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘) %1&$‘

‘‘‘‘‘

‘‘

‘‘

‘‘

WPF Geometry Transformation Tool


The geometry transformer is a simple tool I wrote to scale-, translate- and rotate-transform a
geometry in the path mini language.

Simply paste the geometry string into the input textbox and specify the transform parameters.
After pressing "Transform" the output textbox shows the translated geometry string. This is very
useful to transform simple geometries like an expanded/collapsed chevron used in an expander
template.
‘  ‘ ‘ ‘  ‘   ‘›
 


mages in WPF
ë

' $


! 
‘‘

½
‘) ‘42- %‘  ‘1‘ &‘

‘‘‘
'*‘-11‘
‘6(# %1&$‘

‘‘‘ # ‘# ‘


‘
‘ #  %-11&$‘

‘‘

‘‘‘!)‘-!‘
‘
‘!) %&$‘

‘‘‘-!)%&$‘

‘‘‘-!.2 ‘
‘K;$‘

‘‘‘-!.9)2 ‘
‘E;$‘
c
‘‘‘-!   ‘
‘# $ ‘

‘‘‘-!%&$‘

‘‘‘-!5%&$‘

‘‘

‘‘‘
 ‘-!$‘

‘‘

‘‘

ë

 
"

!
The following method allows you to automatically crop an image to it's content.

‘‘

½ ‘  ‘) ‘(!! %! ‘ &‘

‘‘‘‘‘%‘

‘ &‘

‘‘‘‘‘‘‘‘  ‘
‘()! %  &$‘

‘‘

‘‘‘‘‘%‘8
‘ )JD&‘

‘‘‘‘‘‘‘‘‘
‘
‘! %0‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘  )JD0‘ 0‘;&$‘

‘‘

‘‘‘‘ ‘<2‘
‘2 $‘

‘‘‘‘ ‘2)2‘
‘9)2 $‘

‘‘‘‘ ‘-#‘
‘ ‘‘K$‘

‘‘‘‘ ‘‘
‘<2‘H‘-#$ ‘

‘‘

‘‘‘‘‘!11‘
‘
‘
'2)2‘H‘*$‘

‘‘‘‘!# %!110‘0‘; &$‘

cc
‘‘

‘‘‘‘ ‘!!‘
‘2)20‘!‘
‘;0‘!/1‘
‘<20‘!6)2‘
‘;$‘

‘‘

‘‘‘‘ ‘% ‘#‘


‘;$‘#‘ ‘2)2$‘#>>&‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘ ‘% ‘‘


‘;$‘‘ ‘<2$‘>>&‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘  ‘11‘
‘%#‘H‘‘>‘‘H‘-# &$‘

‘‘‘‘‘‘‘‘‘‘‘‘ 
‘-‘
‘!11 '11*$‘

‘‘‘‘‘‘‘‘‘‘‘‘ 
‘)‘
‘!11 '11‘>‘F*$‘

‘‘‘‘‘‘‘‘‘‘‘‘ 
‘‘
‘!11 '11‘>‘D*$‘

‘‘‘‘‘‘‘‘‘‘‘‘ 
‘!2‘
‘!11 '11‘>‘J*$‘

‘‘

‘‘‘‘‘‘‘‘‘‘‘‘ 7.7 ‘.1‘‘22‘<2‘‘!‘2‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘  ‘2‘
‘!2‘‘F;$‘

‘‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘%2 &‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ !/1‘
‘ 2 %0‘!/1 &$‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ !6)2‘
‘ 2 %0‘!6)2 &$‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ !!‘
‘ 2 %#0‘!! &$‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ !‘
‘ 2 %#0‘! &$‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘

‘‘

‘‘‘‘
 ‘
‘!!! %0‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘
‘JD6 %!/10‘!!0‘!6)2‘ ?‘!/10‘ ‘
c
‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ !‘ ?‘!!&&$‘

‘‘

‘‘

c
3D Graphics
ntroduction to WPF 3D
(1
 
 
The basic idea of creating 3D graphics is to have a three dimensional model of an object.
Because our screen is only two dimensional, we define a camera that takes a picture of the
object. The picture is a projection of the object to a planar surface. This projection is rendered
into an bitmap by the 3D rendering engine. The engine determines the color for every pixel by
calculating the amount of light that is reflected by any light sources to the projection surface by
the objects in the 3D space.
All surfaces of objects have a material and a brush. The material defines how much light is
reflected for a specific angle and the brush defines the color. A brush can either be a simple
color or a gradient or even an image called texture.

 
! 
In the world of 3D graphics, all objects are described by a set of triangles. But why triangles? The
reason for this is that a triangle is the most granular geometry to describe a planar surface. The
rendering engine can calculate the color of each triangl e depending on its material and angle to
the lights in the scene. If we would build our world on rectangles, the points don't need to be
plane. The surface will be a lot more complex to calculate and render.

A surface of a 3D object is called a mesh. A mesh is defined by a number of 3D points. These


points are called vertices. The vertices are joined together by a winding pattern to define the
triangles. Every triangle has a front and a back side. Only the front side is rendered. The front
side is defined by the winding order of the points. WPF uses a counter clockwise winding
pattern. You can remember this with a simple mnemonic called the "right hand rule". This means
if you close your right hand to a thumb -up gesture, your finger make a counter clockwise move

c"
while the thumb shows up. The fingers show the winding order, while the thumb indicates the
upper-side of the triangle.

 !
   
"
WPF uses a right-handed coordinate system. This means that if you hold the fingers of your
right hand as shown on the picture, the fingers indicate the positive direction of the tree axes.

  
(

è‘ @   
The viewport is the control that builds the gate between the 2D and the 3D world.
è‘ i 
Every 3D scene has excactly one camera. The camera defines the  and the
/ . and the :!. of the viewer. WPF supports orthographical and
perspective cameras.
è‘ á 
A 3D model defines an object in the scene. It has a 4# that is the mesh and a

c$
 that can be a diffuse, specular or emmisive material. The material itself has a
brush.
è‘ 
!
Without any lights you see nothing. So we need to place at least one light in our scene
to illuminate our models. WPF supports diffe rent kind of lights, like:
‘ (-/)2
‘ ./)2
‘ /)2
‘ !/)2

ë (3) 3  / $


The following example shows how to create a basic cube mesh with 8 vertices that are wired up
in 12 triangles that form the shape of the cube.

,<!J. ‘

‘‘‘ ,<!J. ‘

‘‘‘‘‘‘ !‘ 


?L;0L;0L; ‘/ .
L;0?L;0?L;‘ ‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ :!.
;0;0F ‘‘

‘‘‘ ,<!J. ‘

‘‘‘ ,J. ‘

‘‘‘‘‘‘ ,J. ‘

‘‘‘‘‘‘‘‘‘ J.4! ‘

‘‘‘‘‘‘‘‘‘‘‘‘ ./)2‘ 


2 ‘.
?F0?F0?J ‘‘

c
‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 4# J. ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 4# J.4# ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 24#J.‘ 


;0;0;‘F;0;0;‘F;0F;0;‘;0F;0;‘
;0;0F;‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ F;0;0F;‘F;0F;0F;‘;0F;0F; ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ )
;‘F‘J‘F‘D‘J‘‘;‘L‘J‘L‘M‘J‘‘L‘E‘M‘L‘G‘E‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ ;‘L‘F‘F‘L‘G‘‘F‘D‘E‘E‘G‘F‘‘D‘J‘M‘M‘E‘
D ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 4# J.4# ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 4# J.  ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ .11 ‘ 2


6 ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 4# J.  ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 4# J. ‘

‘‘‘‘‘‘‘‘‘‘‘‘  J.4! ‘

‘‘‘‘‘‘‘‘‘  ,J. ‘

‘‘‘‘‘‘  ,J. ‘

,<!J. ‘

‘‘

c
Animation
Debugging style and template Errors
iommon Errors
If you get the following error: ' [(6.($.[% %C 
  it could be that you are run into one of the following limitations:

è‘ V‘ ‘ ‘‘    ‘  ‘   ‘


‘‘‘ ‘
è‘ V‘ ‘ ‘‘    ‘  ‘ #
‘  ‘ ‘
‘  ‘‘  ‘


 ‘  ‘
‘ ‘  ‘ ‘  ‘
 ‘  ‘
è‘ V‘ ‘ ‘‘ ‘  ‘
‘   ‘ ‘

ëow to control the frame rate for WPF animations


Animations are very cool, but they can cause a high CPU load. One reason could be a missing
hardware acceleration due to a old graphics adapter or a software rendering constraint. Another
reason could be the the high frame rate of animations that is set to  fps by default.

You can easily lower the framerate for all animations by overriding the >  "0 *
property of the timeline. Just add the following code to your project and play around with the
setting to find a good tradeof f between performance and aesthetic.

‘‘

.6!# 7  % ½


%&0‘

‘‘‘
‘< !# ‘ ‘.1,‘
‘J;‘&$‘

‘‘

‘‘

Or you can set the framerate individually for each animation in XAML, using the following code:

‘‘

.-(‘ #- )!#


7!# ‘.
; ; ;G ‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 
F; ‘
;G ‘ .6
J; ‘‘

‘‘

‘‘

c
Multimedia
ëow to use the Speech Synthesizer in WPF
Microsoft provides a new speech API (SAPI) for Windows Vista and later. It allows developers to
build speech enabled applications. Simply add a reference to !   and include the
following code to your project.

‘‘

 ‘ # !2 #2 $‘

‘‘

!2 #25‘#25‘
‘
‘ !2 #25 %&$‘‘

#25 ,‘
‘G;$‘‘‘;F;;‘

#25 6‘
‘J$‘‘‘‘‘‘?F;F;‘

‘‘

‘ #2 ‘

#25 ! % ‘‘2‘‘ &$‘

‘‘

‘(#2 ‘

#25 ! (# % ‘‘2‘‘ &$‘

‘‘

‘‘

c
Windows 7
ëow to extend the Aero Glass into the Client area

  
Windows Vista has a new default theme called Aero glass. In Aero glass, the title bar of a
window and the frame is drawn transculent. This gives the UI a clean and lightweight look. This
nice feaure is provided by a service that is called the desktop window manager (DWM).

 !1

By default the blurry glass effect is only on the title bar and the frame, but the client area is
drawn opaque. But there is a simple way to extend the glass into the client area by using the
DWM's API.

First thing you need to do is to include some Win32 functions from the "#" library.

‘‘

 ‘ #6!  $‘

 ‘ #<! $‘

 ‘ #<  $‘

 ‘ #< $‘

‘‘

cc
' /# %/#+ N &*‘

   ‘ (64 ‘

‘‘‘‘½ ‘ ‘/12$ ‘

‘‘‘‘½ ‘ ‘6)22$ ‘

‘‘‘‘½ ‘ ‘#!9)2$ ‘

‘‘‘‘½ ‘ ‘#9)2$ ‘

‘‘

'.! % <! &*‘

  ‘

 ‘ ‘‘

‘‘‘.<( %‘20‘ 
‘ (64 ‘!  &$‘

‘‘

'.! % <! &*‘


 ‘  ‘ ‘.<!- %
‘ ‘&$‘

‘‘

‘‘

‘‘

I have written a helper method that does all the stuff to extend the glass by the specified
amount of pixels on each border of the window.

‘‘

‘‘

‘ # ‘

‘‘ 2‘)‘‘‘2‘‘‘1‘2‘<< ‘

‘ # ‘

‘ !‘
<<  ! ‘

‘ !‘
!  ! ‘

½ ‘  ‘ ‘4 %<‘<<0‘2 ‘2  &‘

ccc
‘

‘‘‘‘ ‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘ ‘4-‘
‘;$‘

‘‘‘‘‘‘‘‘.<!- %
‘4- &$‘

‘‘‘‘‘‘‘‘‘% 7 ,, =‘‘G‘BB‘4-‘ ‘;&‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘4‘2‘<<‘2 ‘

‘‘‘‘‘‘‘‘‘‘‘‘ <!9!‘2!‘
‘
‘<!9! %<<&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ 9< ‘< ‘


‘%9<  &9<  ‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 9<%2!9&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ <  !)  ) ‘


‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ ! $‘

‘‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘4‘2‘!‘1‘2‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ #.<)4!2‘ !‘


‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ #.<)4!29<%<  9&$‘

‘‘‘‘‘‘‘‘‘‘‘‘   ‘!@‘
‘ !.!@‘‘IE$‘

‘‘‘‘‘‘‘‘‘‘‘‘   ‘!A‘
‘ !.!A‘‘IE$‘

‘‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘ ‘ ) ‘

‘‘‘‘‘‘‘‘‘‘‘‘ (64 ‘)‘


‘
‘ (64 %&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ )/12 ‘
‘% &%2 /1‘H‘!@&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ )6)22 ‘
‘% &%2  6)2‘H‘!@&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ )#9)2 ‘
‘% &%2  ‘H‘!A&$‘

‘‘‘‘‘‘‘‘‘‘‘‘ )#!9)2 ‘
‘% &%2 !‘H‘!A&$‘

‘‘

‘‘‘‘‘‘‘‘‘‘‘‘ << ) ‘


‘2! $‘
cc
‘‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘2‘
‘.<( %<  90‘‘

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘ 
‘)&$‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘‘‘‘

‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ << ) ‘


‘ # <2 $‘

‘‘‘‘‘‘‘‘‘

‘‘‘‘‘

‘‘‘‘ ‘%.! &‘

‘‘‘‘ ‘

‘‘

‘‘‘‘‘

‘‘

‘‘

Next thing you need to do is calling the +  "A  in the    "
callback. Because that is the time the window handle has been created.

‘‘

‘‘

½

‘ 

‘ ‘7 5 %()‘ &‘

‘‘‘
7 5 %&$‘

‘‘‘49! 4 % 0‘/#6 )&$‘

‘‘

‘‘

‘‘

cc
Since the user (or the system) can enable or disable the glass effect while the application is
running, we need to hook up a callback in the "  to undo or initialize the glass extension
dynamically.

‘‘

‘‘

½
‘‘ %‘2<0‘  ‘)0‘‘<0‘ ‘

‘‘‘0‘ 
‘ ‘2&‘

‘‘‘‘‘%)‘

‘49!  ". 7 7 79(4. &‘

‘‘‘‘ ‘

‘‘‘‘‘‘‘‘49! 4 % 0‘/#6 )&$‘

‘‘‘‘‘‘‘‘2‘
‘$‘

‘‘‘‘‘

‘‘‘‘
 ‘O$‘

‘‘

‘‘

‘‘

ëow to use the Windows Vista TaskDialog in WPF

cc"
‘

  
Windows Vista comes with an new standard dialog box called task dialog. The TaskDialog was
developed as part of Windows Vista's "clarity" offensive to improve the user experience. It
provides a lot more features than the original message box.

The TaskDialog is part of the   G5" library and only available on Windows Vista or
later, its not part of WPF or the .NET framework. To use it from managed code, we need to write
a interop wrapper.

This article is not finished yet... : -(

ëow to add Tasks to Jumplists in .NET 4.0 and Windows 7

  

cc$
Windows 7 provides a new taskbar feature for applications called jumplists. They appear, when
you right-click on a application icon in the taskbar. By default you see a list of recent files
opened and two entries to launch and detach the application.

.NET 4.0 provides a managed API that allows you to easily manipulate the entries in the jumplist.

ë

'
<   
A jumplist is nothing more than a categorizes list of links to files that can be launched by the
user. The links are called X
. They can be parametrized with a title, description, icon,
filepath and command line arguments.

In the following sample I create a new X8 and add a task to the list that launches the
sample application, but with a command line argument. If the application is launched with an
argument, it shows a MessageBox instead.

‘‘

½ ‘!‘‘(!!‘ ‘(!! ‘

‘‘‘‘½

‘ 

‘ ‘7 !% !()‘ &‘

‘‘‘‘ ‘

‘‘

‘‘‘‘‘‘‘‘‘%()%&‘‘;&‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ ) 2<% A‘2‘2‘‘ &$‘

‘‘‘‘‘‘‘‘‘‘‘‘ 2<%&$‘

‘‘‘‘‘‘‘‘‘

‘‘

‘‘‘‘‘‘‘‘P! ‘ ‘
‘
‘P! ‘

‘‘‘‘‘‘‘‘ ‘

‘‘‘‘‘‘‘‘‘‘‘‘ ‘
‘ 2 ‘1‘:! 0‘

‘‘‘‘‘‘‘‘‘‘‘‘ ()‘
‘ ! 0‘

‘‘‘‘‘‘‘‘‘‘‘‘ .!‘
‘ 2 ‘1‘ 1<‘:! 0‘

‘‘‘‘‘‘‘‘‘‘‘‘ )#‘
‘ ( 0‘

‘‘‘‘‘‘‘‘‘‘‘‘ 62‘
‘(-# 4#(-# %&0‘

cc
‘‘‘‘‘‘‘‘‘‘‘‘ (!!2‘
‘(-#4#(-# %&‘‘

‘‘‘‘‘‘‘‘$‘

‘‘

‘‘‘‘‘‘‘‘P!/‘=!/‘
‘
‘P!/%&$‘

‘‘‘‘‘‘‘‘=!/P! (% &$‘

‘‘‘‘‘‘‘‘=!/ 2<N)# ‘
‘1$‘

‘‘‘‘‘‘‘‘=!/ 2<6)# ‘
‘1$‘

‘‘

‘‘‘‘‘‘‘‘P!/ P!/ %(!! 0‘=!/ &$‘

‘‘‘‘‘

‘‘

‘‘

cc
nteroperability

ë!ë
 
)*)  
‘‘

‘<<9‘
‘
‘<!9! %‘

‘‘‘‘(!!  < &9$‘

‘‘

‘‘

cc


Performance
50 WPF Performance Tips
 
  
 

1.‘ Disable Assembly localization if you don't need it. By using the
'6/))(-*

cc
Expression Olend
Prototyping with Expression Olend 3 + SketchFlow

  
Software is getting even more complex, interactive and dynamic. It's nearly impossible, for a
developer to find the best solution at first time. If you start writing code without testing the
concept, you can throw away a lot of valuable time by following a suboptimal approach.

' 
   
The idea of SketchFlow is to combine the simpleness and informality of sketching with paper
and pencil with the dynamic of interactive prototypes. Most prototyping tools focus on creating
high quality assets, but the main purpose of most prototypes is to proove the interaction de sign
of your software and not to impress your management.

To address this point the Team of SketchFlow has created special styles for controls that look as
if they where drawn by pencil. This focus the discussion on real interaction problems instead of
discussing about details like colors or fonts and suggests that the screen design is still
changeable with a small effort.

c
‘

)
 
Expression Blend 3 includes a workspace management feature that allows you to hide all panels
you don't need to sketch your prototype. You can save your settings by choosing "Save as new
Workspace" from the "Windows" menu.

/

  +
In Blend 3.0 you find two new project types to create prototypes for WPF or Silverlight.

/

 

cc
‘
‘

(" 
In the asset library you will find a new category "SketchFlow". It contains a section called "Sketch
Styles". It contains special styles for most WPF or Silverlight controls that look like they are
drawn by hand.

c
‘
‘


 
 
If you have a part that is used on multiple screens, like a navigation or a login box, you can
extract it to a component screen. This screen can be referenced on multiple screens. If you
modify the component screen, the changes are reflected to all screens.

c
‘
‘

‘
‘

) 3 
 !
 

c"
‘

 
 


A prototype needs to provide sample data to make it understandable. In flash prototypes,


sample data is often just a bunch of textblocks and images. In SketchFlow we have a sample
data generator, that creates real data sources that can be bound to lists and elements as real
data. Selection, scrolling and sorting all works.

In the Data panel you find a database icon. It allows you to create a new sample data source .

c$
Give the sample data source a name and specify the scope of visibility. This can be only on this
screen or within the whole prototype. This can be useful, if you want to use the same demo data
on multiple screens.

After creating the demo data source, you can define how a data record should look like. You can
add properties or most popular types and choose from a variety of sample data types. There are
URL's, e-mail adresses, bild text (lorem ipsum), images, and much mure...

c
‘
‘

 
 *2 
** 

c
‘
‘

'"
 ! $


c
‘
‘

‘
‘

c
‘
‘

1
"  
 
When you have finished your prototype, you can generate a design documentation by a single
click. It includes the a table of content, the flow m ap and screenshots of all screens and
components. It's not meant to use it as a complete documentation, but it's a good start to build
on.

c
cc
ëow to mport Photoshop Files into WPF
  
In a WPF project you often have to deal with assets that are created by a designer. They are
often part of Adobe Illustrator or Photoshop files. There are two ways to achieve this goal. You
can

è‘  "#  !!$   


This is the most simple approach if you have Expression Blend 3. Drawbacks are, that you
can only import vector shapes as 2 elements. If you want to add these shapes into
the resources, you have to manually extract the geometries.
è‘ #  !!$   
 %?á
This approach requires Expression Design to be installed but works already with Version
2.0. The workflow is a bit more complex, but you can choose if you want to export your
shapes as 2 or 4 .

*
 !* 
If you create graphical assets that should be integrated to a WPF project you should think of the
following rules to make the import easier.
c
è‘ i      !  to one shape
è‘ &  "   , because they are mostly ignored by the converter
è‘ à !   '. Higher color depts cause errors on import

(  " *    


The following tutorial explains how to directly import an Adobe Photoshop file into WPF.

è‘ c‘  ‘|

‘" ‘‘ ‘‘  ‘ !‘$  ‘


è‘
‘
‘%& ‘ ‘  
‘! %‘‘  ‘%! %‘ ‘

‘
è‘ j‘   ‘  ‘ ‘ ‘  ‘ ‘ ‘ ‘" ‘
è‘ ‰‘ ‘‘ ‘  ‘ 
‘ ‘  ‘ ‘ ‘‘‘'()*‘

c
è‘ 5. Blend imports the file now. Each layer will create a new ) or 2 element. The
images will automatically be added to a separate folder in your project.

ëow to convert Path to Resources


To convert imported  objects to A  ! objects that can be consumes as resources you
have to do the following steps:

è‘ c‘ ‘  ‘  ‘‘  ‘%  %‘  ‘ ‘  ‘‘

‘
è‘ 2. Create a 4# object and paste the content between the opening and
closing tag. Give the geometry a unique key.

 *   ( !


 ,á-
The following tutorial explains how to import Adobe Photoshop Files in Expression Design and
Export to XAML to use it in Expression Blend.

è‘ c‘  ‘|

‘" ‘‘ ‘  ‘
 ‘  
‘! ‘
è‘
‘ ‘‘ ‘  ‘ 
‘ ‘  ‘ ‘ ‘‘‘'()*‘

c"
è‘ 3. Open the Options Dialog in "Edit ->Options->Clipboard(XAML)" and choose if you
want to export shapes as  or 6‘. .

è‘ ‰‘   ‘  ‘$ 
‘ ‘  ‘ ‘  ‘‘
‘% ‘%‘‘  ‘| ‘ ‘

‘
è‘ Î‘ ‘‘ ‘|

‘" ‘ 
‘  ‘‘
 ‘‘  ‘‘

c$
Expression Olend 2 Addns

  
Expression Blend has an add-in model that allows developers to write add-ins to extend its
functionality. Unfortunately this is mainly unknown to most users of blend. A prominent
example is the intellisense addin for blend.

*
 

è‘ — ‘+‘&‘ ‘‘|

‘" 
è‘  ‘+‘
‘‘
‘‘‘  
è‘ ‘+‘

‘‘
‘‘ ‘) 
è‘ " 

‘+‘"
‘&  
‘ ‘|

‘" 

ë-

 ÷ 
 
To load and run an addin into expression, just pass a command parameter ?"" followed the
name of the add-in dll. You don't need any registration of plug -ins, but you can load only one
addin on the same time. To get over this limitation you can use an add -in manager that
dynamically loads multiple plugins even without restarting the tool.

 Q)‘ Q 1‘! Q‘DQ‘


 712( ‘

‘‘

c
Tools
XAMÔ Converters
The following list shows converters developed by the WPF community to convert different
formats to XAML or vice versa.

è‘  ‘&
 ‘‘| ‘ 
è‘  ‘  
‘ ‘‘  
è‘ "  ‘‘| ‘ 
è‘   ‘‘| ‘ 
è‘ @
‘‘|
è‘ j ‘ ‘‘ ‘‘  
è‘  ‘ ‘‘  
è‘ !
‘ ‘‘  
è‘ @ ‘ ‘‘  
è‘ !,|!‘ ‘‘  

Debugging and Development —tilities

è‘ ‘  ‘›

è‘  ‘‘@
‘ 
è‘ ‘+‘‘  ‘‘
‘ ‘  

è‘    ‘+‘@ ‘

‘‘ 

è‘  ‘ ‘  ‘ 
è‘  ‘+‘‘
‘—&‘
‘‘ !‘ ‘  

è‘ -|›‘+‘‘  ‘ ‘‘
 ‘ ‘ ‘

‘ 
‘‘-|›‘ 

XAMÔ Editors

è‘ ‘ 
è‘ ‘ ‘.   /
è‘ ‘0
è‘ )
c
Graphical WPF Designers

è‘ ‘‘‘
 
è‘ X‘j ‘.j ‘‘›‘ ‘|  ‘÷/

c