Introduction about
Windows Presentation Foundation
                 Trainer: Thoai Nguyen
                 Duration: 4 hours
                                    1
Agenda
•   Introduce WPF
•   XAML
•   Dependency Properties and Routed Events
•   Commands in WPF
•   Resources & Styles in WPF
•   Control Templates
•   Data Binding
•   Data Templates
                                              2
What is WPF?
• WPF = Windows Presentation Foundation
  (Avolon)
• An Engine?
• A graphical display system for Windows
• Set of .NET libraries?
                                           3
WPF uses DirectX
WPF applications use DirectX no
matter what type of user interface
you create
   .NET Framework     WPF     DirectX
                    Windows
                                        4
Resolution Independence
  WPF bases its scaling on the system DPI
   setting
                                            5
The Evolution of WPF
 • WPF 3.0
 • WPF 3.5 & VS.NET 2008
                           6
New Features in WPF 3.5
• Firefox support for XBAPs
• Data binding support for LINQ
• Data binding support for
  IDataErrorInfo.
• Support for placing 2-D elements on
  3-D surfaces.
• …
                                        7
WPF will replace Windows FORM?
• Windows FORM : mature
• WPF : future enhancements and longevity
                    Windows Form is still
                    supported…
                    No need to recode my
                    application for WPF
                                            8
Silverlight
•   Is a subset of WPF
•   Silverlight 1.0: Javascript
•   Silverlight 2.0: .NET languages
•   Silverlight 3.0: Improve performance
•   Silverlight 4.0: still Beta atm
                                           9
Silverlight vs Flash?
• Flash is mature
• Silverlight is future
  – Development IDE
  – .NET Framework & Languages
  – Perception
  – Microsoft has Windows
  –…
• Demo: http://www.shinedraw.com/flash-vs-
  silverlight-gallery/
                                             10
Architecture of WPF
 PresentationFramework.dll
                                                  Managed
                                                  WPF API
    PresentationCore.dll     WindowsBase.dll
                                                    Media
        milcore.dll          WindowsCodecs.dll   Integration
                                                    Layer
         Direct3D                 User32
                                                          11
The Last Word
•   Hardware acceleration
•   Resolution independence
•   No fixed control appearance
•   Declarative user interfaces
•   Object-based drawing
                                  12
What is XAML?
• Extensible Application Markup Language,
  and pronounced “zammel”
                                            13
Graphical User Interfaces Before WPF
• Hard to separate the graphical content from the code
   – Each graphical element (background, button, and so on) needs to
     be exported as a separate.
   – User interface logic needs to be embedded in the code.
   – ..
   – Designers don’t work on VS.NET
                                                                       14
The Variants of XAML
•   WPF XAML
•   XPS XAML
•   Silverlight XAML
•   WF XAML
                       15
XAML Compilation
                             assembly
       XAML
                            Embedded
        C#                  resource
      images
                                  BAML
BAML = Binary Application Markup Language
                                         16
XAML Basics
• Every element = an instance of a .NET
  class
• Allow nested elements
• Can set the properties of each class
  through attributes
                                  XAML Demo
                                              17
Properties and Events in XAML
•   Simple Properties and Type Converters
•   Complex Properties
•   Markup Extensions
•   Attached Properties
•   Nesting Elements
•   Special Characters and Whitespace
•   Events
                                            18
Understanding Dependency Properties
• Dependency Properties are:
  – not normal properties
  – the basis for a number of key WPF
  – wrapped by ordinary .NET property procedures
                                               19
Defining and Registering a Dependency Property
• They are :
  – represented by read-only static fields
  – registered in a static constructor
  – wrapped by a standard .NET property
• Example
                                             20
How WPF Uses Dependency Properties?
• change notification
• dynamic value resolution.
                                      21
Understanding Routed Events
• Allows an event to originate in one element
  but be raised by another one
                                                22
Defining and Registering a Routed Event
• They are :
  – represented by read-only static fields
  – registered in a static constructor
  – wrapped by a standard .NET event definition
• Example
                                                  23
Event Routing
•   Direct events
•   Bubbling events
•   Tunneling events
•   Handling a Suppressed Event
• … Example
                                  24
What is Attached Events?
• Scenario with a Stack Panel
  <StackPanel Button.Click="DoSomething" Margin="5">
        <Button Name="cmd1">Command 1</Button>
        <Button Name="cmd2">Command 2</Button>
        <Button Name="cmd3">Command 3</Button>
        ...
  </StackPanel>
• pnlButtons.AddHandler(Button.Click, new
  RoutedEventHandler(DoSomething));
                                                       25
Commands
• Limitation of Events
• WPF fills in the gaps with a new commanding model
                                                      26
Still has some fairly significant gaps
• Command tracking
• “Undoable” commands
• Can be in different “modes”
                                         27
The WPF Command Model
• The ICommand Interface
• The RoutedCommand Class
• The RoutedUICommand Class
                              28
Executing Commands
• Command Sources
  <Button Command="ApplicationCommands.New">New</Button>
  <Button Command="New">New</Button>
                                                           29
Executing Commands
• Command Bindings
        <Window.CommandBindings>
            <CommandBinding
// Create the binding.
CommandBinding     binding = new CommandBinding(ApplicationCommands.New);
        Command="ApplicationCommands.New"
// Attach the event handler.
binding.Executed Executed       ="NewCommand" />
                   += NewCommand_Executed;
         </Window.CommandBindings>
// Register the binding.
this.CommandBindings.Add(binding);
                                                                            30
Advanced Commands
• Custom Commands
• Using the Same Command in Different
  Places
• Using a Command Parameter
• Tracking and Reversing Commands
        DO IT YOURSELF
                                        31
Short introduction about Resources
• Assembly Resources
• Object Resources
     <Window.Resources>
               <ImageBrush x:Key="TileBrush"
                              TileMode="Tile"
  <Button Background="{StaticResource   TileBrush}“
                              ViewportUnits="Absolute"
           Margin="5" Padding="5"
           FontWeight="Bold" Viewport="0 0 32 32"
           FontSize="14">
  A Tiled Button
                              ImageSource="happyface.jpg"
  </Button>                   Opacity="0.3">
               </ImageBrush>
     </Window.Resources>
                                                            32
Need a font for all controls?
<Window.Resources>
   <FontFamily
<Button        x:Key="ButtonFontFamily">Times
        Padding="5" Margin="5" Name="cmd"      New Roman</FontFamily>
   <sys:Double  x:Key="ButtonFontSize">18</sys:Double>
        FontFamily="{StaticResource ButtonFontFamily}"
   <FontWeight x:Key="ButtonFontWeight">Bold</FontWeight>
        FontWeight="{StaticResource ButtonFontWeight}"
</Window.Resources>
        FontSize="{StaticResource ButtonFontSize}" >
A Customized Button
</Button>
                                                                  33
What do styles add to the picture?
• We use style instead
<Window.Resources>
       <Style x:Key="BigFontButtonStyle">
       <Setter Property="Control.FontFamily" Value="Times New Roman" />
<Button Padding="5" Margin="5" Name="cmd"
       <Setter Property="Control.FontSize" Value="18" />
        Style="{StaticResource BigFontButtonStyle}"
       <Setter Property="Control.FontWeight" Value="Bold" />
       >A Customized Button
       </Style>
</Button>
</Window.Resources>
                                                                     34
Creating a Style Object
•   Setters
•   Triggers
•   Resources
•   BasedOn
•   TargetType
    Example
                          35
Style Triggers
•   Trigger
•   MultiTrigger
•   DataTrigger
•   MultiDataTrigger
•   EventTrigger
    Example
                       36
Control Templates - Logical Trees
<Window x:Class="SimpleWindow.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SimpleWindow" Height="338" Width="356" >
       <StackPanel Margin="5">
           <Button Padding="5" Margin="5">First Button</Button>
           <Button Padding="5" Margin="5">Second Button</Button>
       </StackPanel>
</Window>
                                                                            37
Control Templates - Logical Trees
                                    38
Control Templates - Visual Trees
                - Alter one of the elements in the visual tree
                using styles
                - Create a new template for your control
                                                Simple Window
                                                   Example
                                                                 39
Control Templates
• Want a window like this?
                             40
Creating Control Templates
• A Simple Button
  <Window.Resources>
   <Button Margin="10" Padding="5"
     <ControlTemplate x:Key="ButtonTemplate"
           Template="{StaticResource    ButtonTemplate}“>
                      TargetType="{x:Type Button}">
          A Simple Button with a Custom Template
         <Border BorderBrush="Orange" BorderThickness="3"
   </Button>
                 CornerRadius="2"
                 Background="Red"
                 TextBlock.Foreground="White">
                 <ContentPresenter RecognizesAccessKey="True">
                 </ContentPresenter>
         </Border>
     </ControlTemplate>
  </Window.Resources>
                                                                 41
Template Triggers
• Need more visual effect?
 <ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
            <ControlTemplate.Triggers>
                      <Trigger Property="IsMouseOver" Value="True">
                                 <Setter TargetName="Border" Property="Background"
                                         Value="DarkRed" />
                      </Trigger>
                      <Trigger Property="IsPressed" Value="True">
                                 <Setter TargetName="Border" Property="Background"
                                         Value="IndianRed" />
                                 <Setter TargetName="Border"
                                         Property="BorderBrush" Value="DarkKhaki" />
                      </Trigger>
            </ControlTemplate.Triggers>
 </ControlTemplate>
                                                              Example Simple Button
                                                                                       42
TEMPLATES VS. STYLES
• Both allow you to change the
appearance of an element
•Slyle can’t change visual tree
                                  43
Advanced Templates
• Organizing Template Resources
• Building More Complex Templates
        DO IT YOURSELF
                                    44
Data Binding
• is extract some information from a source
  object and use it to set a property in a
  target object
 Example Binding to the Properties of an
 Element….
                                              45
Binding Direction
•   OneWay
•   TwoWay
•   OneTime
•   OneWayToSource
•   Default
                     46
Binding Updates
•   PropertyChanged
•   LostFocus
•   Explicit
•   Default
                      47
Binding to Objects That Aren’t Elements
• The only requirement is that the information
  you want to display must be stored in public
  properties
• Use 1 of 3 options:
  – Source
  – RelativeSource
  – DataContext
                                             48
Binding using Source
 <Window.Resources>
        <FontFamily x:Key="CustomFont">Calibri</FontFamily>
 </Window.Resources>
 <TextBlock
        Text ="{Binding Source={StaticResource CustomFont},
        Path =Source}">
 </TextBlock>
                                                              49
Binding using RelativeSource
<TextBlock>
   <TextBlock.Text>
      <Binding Path="Title">
       <Binding.RelativeSource>
           <RelativeSource Mode="FindAncestor"
                             AncestorType="{x:Type Window}" />
        </Binding.RelativeSource>
     </Binding>
   </TextBlock.Text>
</TextBlock>
<TextBlock
   Text="{Binding Path=Title,
          RelativeSource={RelativeSource FindAncestor,
                            AncestorType={x:Type Window}}}">
</TextBlock>
                                                                 50
Binding using DataContext
• When many elements bind to 1 object
 <StackPanel DataContext="{x:Static SystemFonts.IconFontFamily}">
    <TextBlock
      Text="{Binding Source={x:Static SystemFonts.IconFontFamily},
      Path=Source}">
    </TextBlock>
    <TextBlock
       Text="{Binding Source={x:Static SystemFonts.IconFontFamily},
 <StackPanel  DataContext="{x:Static SystemFonts.IconFontFamily}">
       Path=LineSpacing}">
 …. </TextBlock>
         <TextBlock Margin="5"
    <TextBlock
       Text="{BindingText="{Binding  Path=Source}"></TextBlock>
                      Source={x:Static SystemFonts.IconFontFamily},
       Path=FamilyTypefaces[0].Style}">
    </TextBlock>
    <TextBlock
       Text="{Binding Source={x:Static SystemFonts.IconFontFamily},
       Path=FamilyTypefaces[0].Weight}">
    </TextBlock>
 </StackPanel>
                                                                  51
Binding to a Collection of Objects
• 3 properties:
  – ItemsSource
  – DisplayMemberPath
  – ItemTemplate
  – Demo…
                                     52
Data Conversion
•   Implements IValueConverter
•   Add the [ValueConversion] attribute
•   Implement a Convert() method
•   Implement a ConvertBack() method
Demo…
                                          53
Data Template
• to customize the way each item is shown in
  an ItemsControl
• is a chunk of XAML markup that defines
  how a bound data object should be
  displayed
  ItemsControl: ListView, ListBox, ComboBox, etc
  ContentControl: Panel, etc
                                                   54
DataTemplate Example
<ListBox
<ListBox Name="lstContacts">
         Name="lstContacts"
     <ListBox.ItemTemplate>
DisplayMemberPath=“FullName">
         <DataTemplate>
</ListBox>        <TextBlock Text="{Binding Path=FullName}">
                  </TextBlock>
         </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>
                                                               55
Second DataTemplate Example
• View Demo
                              56
Varying Templates
• Use a data trigger
• Use a value converter
• Use a template selector
                            57
Template Selectors
• Inherit class DataTemplateSelector
• Implement method SelectTemplate()
  View Demo
                                       58
Templates and Selection
• If you select an item in the list, WPF
  automatically sets the Foreground and
  Background properties of the item container
  View Demo
                                            59
Exercise & Question?
                       60