TOOL DEVELOPMENT
WPF & XAML
2023 – 2024   Digital Arts & Entertainment
WHAT IS WPF?
Windows Presentation Foundation
• Presentation Framework for Windows-Based
  applications with a strong focus on UI
   •   Windows Desktop
   •   Windows Store App
   •   Xbox One (UWP – Universal Windows Platform)
   •   …
• Free and Open Source
   • Part of .NET Framework & .NET Core
• Widely used for Enterprise Applications
   • Applications for internal use (Tools)
   • Example: Rockstar Games (Asset Browser,
     Terrain Manager, …)
MAIN FEATURES
• Designer Friendly (XAML)
   • Layout
   • Support for 2D / 3D Graphics, Media,
     Animations
   • Styles and Templates
• Data Binding
   • Visuals update automatically when data
     changes
   • Input fields / sliders can be linked to the data
     directly
XAML + C#
• Markup (.xaml) + Code-behind (.xaml.cs)
• .xaml
    • Define the appearance (Components,
      Layout, Color)
• .xaml.cs
    • Functionality that responds to user
      interaction
    • Links visuals to data
    • Business logic
XAML
EXTENSIBLE
APPLICATION MARKUP
LANGUAGE
•   Separates UI from
    Behavior
•   Designer Friendly
•   Based on XML
                               XML
<game>                         • Data Transport
      <name>Ring fit           • Text based, Readable format
adventure</name>
      <publisher>Nintendo</    • No execution logic: Needs software to
publisher>                       process
     <release>2019</release>
</game>
                               Main uses:
                               • Configuration files
                               • Communication between applications
                                 (e.g., client – server)
                                          XML STRUCTURE – TAGS
<games>                                   <element/>
       <game>
                <name>Wii Sports</name>   <element>…</element>
                <publisher>Nintendo</
publisher>                                • Can hold other elements
              <release>2006</release>
       </game>                            • Can hold a single piece of data
       <game>                               (string, number, boolean,…)
              <name>Just Dance</name>
              <publisher>Ubisoft</        • Only one root element
publisher>
              <release />
       </game>
       <game>
              <name>Ring fit
adventure</name>
              <publisher>Nintendo</
publisher>
              <release>2019</release>
       </game>
</games>
                                             XML STRUCTURE –
                                             ATTRIBUTES
                                             <element attribute=“some value” />
<games>                                      • Multiple (unique) attributes allowed per
       <game id=“f239af3d“ release=“2006“>
              <name>Wii Sports</name>          tag
              <publisher>Nintendo</
                                             • info about the element itself
publisher>
              <release>2006</release>        • Easy to search / filter
       </game>
       <game id=“4ebd0208“>
              <name>Just Dance</name>
              <publisher>Ubisoft</
publisher>    </game>
       <game id=“6a23dabe“ release=“2019“>
              <name>Ring fit
adventure</name>
              <publisher>Nintendo</
publisher>
       </game>
</games>
                                             XML STRUCTURE
                                             • Comments:
<games>
       <game id=“f239af3d“ release=“2006“>   <!-- Everything between these tags is a
              <name>Wii Sports</name>        comment. -->
              <publisher>Nintendo</
publisher>                                   • XML SCHEMA
              <release>2006</release>           • Can be defined to force a fixed
       </game>                                    structure
       <workoutGame code=“4ebd0208“>
                                                • Predefined tags / attributes
              <name>Just Dance</name>
              <publisher>Ubisoft</           • Examples:
publisher>    </workoutGame>
       <!-- my favorite -->                     • HTML
       <Game id=“6a23dabe“ year=“2019“>         • XAML
              <name>Ring fit
adventure</name>
              <publisher>Nintendo</
publisher>
       </Game>
</games>
  XAML & WPF
WPF PROJECT
  SETUP
    PROJECT CREATION
Visual Studio >> File >> New >>
Project…
Select WPF Application
Solution Explorer:
• App.xaml(.cs)
     •   Starting point of application
     •   All application-wide properties /
         initialization logic / …
•   MainWindow.xaml(.cs)
     •   The window that is displayed when
         the app starts.
     •   Logic / content of that specific window
 XAML & WPF
.xaml file
 XAML VIEW & DESIGN
 VIEW
Linked together:
Modifying XAML code has direct effect
on the Design View -> Immediate
feedback
Buttons for switching the
views / changing layout
XAML EXAMPLE
XAML EXAMPLE
               ?
XAML EXAMPLE – BUTTON CONTENT
XAML GENERATING
METHODS
1. Typing XAML code manually
    [+] Good IntelliSense /
    autocomplete
    [+] Keep overview of XAML code
    [+] No unwanted properties
    [-] Steep Learning curve
2. ToolBox (elements)
    [+] Easy Drag & Drop
    [+] Overview of all possible
    elements
    [-] Messy XAML code
3. Properties (attributes)
    [+] Overview of all possible
    properties
    [-] Some properties are not
    intuitive / easy to find
Tip: Type as much as possible, use
ToolBox and Properties only when
needed
         CODE GENERATED UI
         1. Creating UI elements in C#
            code
             [-] No design viewer
             [-] More code
             [-] No separation of code / UI
             [-] Not easily modifiable
         Watch out for answers on Stack
DON’T!
         Overflow that suggest this!
              EXERCISE: Basic XAML
•   Get the image RubenVanostayen.jpg from Leho
•   Add to the project (Resources folder)
•   Set image type to “Resource” through properties
•     MainWindow.xaml:
    •    Size: 450x450
    •    Background: Black
    •    Image
       •    Align: Bottom Right
       •    Size: 300x200
       •    20 px away from sides
              EXERCISE: Basic XAML
•   Change the Fill type of the image:
XAML & WPF
.xaml.cs file
    Code Behind
    Partial class:
    •   A class that is split into multiple code
        files.
    •   .xaml file is generated into a
        second .cs file -> a partial class of
        the same type.
    InitializeComponent()
    •   Loads the contents of the XAML file
    •   Generates objects graph to display
     Don’t remove this method!
!
Accessing elements from
code
Providing the name (x:Name) in
xaml makes the element accessible in
code behind
Adding behavior
1. From C# code
    [+] clear overview of handled
    events
    [-] depends on specific UI
    [-] Removing element will cause
    error
2. From .xaml
    [+] less dependence on specific UI
    [-] less overview of handled events
          EXERCISE: Adding behavior
• Create field in code-behind:
          double _scale = 1.2;
• When mouse hovers over the image,
  multiply its width & height with _scale
• When mouse leaves the image,
  divide its width & height with _scale
All done? Try this:
      When mouse hovers over image, hide
      it
      When mouse goes back out, reveal
      again
     Something seems to go wrong, but why?
      WPF
Layout Containers
   STACKPANEL
Order of controls is the same as order in xaml
• Remaining space is left open
• If not enough space, overflows
• Orientation: Vertical by default (top to
  bottom)
• Orientation: Horizontal (left to right)
GRID LAYOUT
                                    sum: 2 + 1 = 3*
                                    > first row: 2/3
                                    > second row:
                                    1/3
                             default width =
                             1*
                             > sum: 1+1+1 =
                             3*
                             > each col: 1/3
• Rows & Columns, proportional width/height
• Attached properties to set row/col of child elements
   ATTACHED
   PROPERTIES?
• Defined in one class
• Set on objects of another class
Example: Grid.Row / Grid.Column for Image
• Image class doesn’t (shouldn’t) know about
  Column & Row properties.
• Properties are defined inside of Grid Class
• Available in elements that are direct child
  of Grid
• Grid class evaluates the attached properties
  of its direct children and will set position
  accordingly.
   GRID LAYOUT
• Order is not important (except for
  overlapping elements)
• Elements are placed in a certain row /
  column
• Resizing keeps the layout proportional by
  default
• By default, elements fill the whole cell
   • Can be changed with
      VerticalAlignment &
      HorizontalAlignment of the child
      element
VerticalAlignment &
HorizontalAlignment
• Overview of different combinations
• In Grid: default = Stretch, Stretch
MARGIN & PADDING
• Margin = space around the
  object
• Padding = space inside the
  object,
  around the content
                                                Margin
                                                             Padding
• BorderThickness
All take in a “Thickness” value,
                                                     BorderThickness
expressed in 1, 2 or 4 numbers:
•   1 number: left = top= right = bottom
    margin=“13”
•   2 numbers: left=right, top=bottom
    margin=“10,20”
•   4 numbers: clockwise, starting with left:
    left, top, right, bottom
    margin=“5,10,20,8”
    CANVAS
•   Fixed position for each element
•   Useful for graphs, custom content
    drawing (e.g., level editor, node based
    editor,…)
 UNIFORMGRID
Arrange objects into uniform grid regions
[!] WPF ONLY
    WRAPPANEL
•   Arrange objects from left to right
•   wraps content
[!] WPF ONLY
    DOCKPANEL
•   Dock elements against sides of the
    container
•   Useful for panels around content area:
     • toolbar at the top
     • properties panel
[!] WPF ONLY
    LAYOUT TIPS & TRICKS
•   Choose the correct layout container
    •   Grid (most preferred)
    •   StackPanel (in more specific cases)
    •   Others: if the two above don’t suffice
•   Set the alignment within the container
    •   HorizontalAlignment &
        VerticalAlignment
•   Set a margin and padding if needed
    •   optional: add a Border control
  XAML & WPF
STATIC RESOURCES
    STATIC RESOURCES
•   The same set of colors is being reused
    for various items
•   All titles should have the same style
What if the designer wants to change the
theme to purple instead of yellow?
 Making variables for XAML
    STATIC RESOURCES
•   Add resources to a container
    •   Container = any element type that can
        hold other elements:
        Grid, Window, ListBox, StackPanel, Button,…
    •   Resources will become available to all
        elements inside this container
    •   TIP: You can define application-wide
        resources in App.xaml using
        <App.Resources>
•   Key for each resource
    •   items in xaml refer to this key using
        StaticResource
    •   markup extensions: { }
    STATIC RESOURCES - TYPES
•   SolidColorBrush is in the WPF
    namespace
•   Int32 is in the mscorlib namespace
      • not included by default
Solution: Add namespace to the XAML file
    STATIC RESOURCES - STYLES
•   Defining visual style for all elements of a
    specific type inside of a container:
 XAML & WPF
ITEM TEMPLATES
WORKING WITH DYNAMIC
CONTENT
•   Display a collection of data
•   Amount of elements is unknown
    beforehand
COLLECTIONS: LIST<T> TYPE
• Variable number of elements
• add / insert / remove elements
  at runtime
• Equivalent to c++ std::vector<T>
LISTBOX: ITEMSSOURCE              MainWindow.xaml:
• Listbox data can be set using
  “ItemsSource” property
• By default: shows text only:    MainWindow.xaml.cs:
LISTBOX: ITEMSSOURCE               MainWindow.xaml:
• ItemsSource can be of any type
• Custom class shows the name of
  the class, not the content       MainWindow.xaml.cs:
• ToString() is used by default
                                   Result:
LISTBOX - ITEMTEMPLATE
• Define a visual template for the
  ListBox
• This template is automatically
  copied for each ListBox Item.
• Binding XAML to C# Properties
Result:
    BINDING
Inside the ItemTemplate of a ListBox:
•   Use markup extensions: { } to bind to a
    property
•   ItemsSource of the listbox set to a
    List<T>:
•   Binding will look for this property inside
    the Type T
DataBinding in WPF / XAML:
•   To be continued in MVVM (in 2 weeks)