Introduction to XAML and WPF

Preview:

Citation preview

Introduction to WPFIntroduction to WPFNext Generation for Desktop Next Generation for Desktop

Applications Applications

Doncho MinkovDoncho Minkov

Telerik School Telerik School AcademyAcademyschoolacademy.telerik.com

Technical TrainerTechnical Trainerhttp://www.minkov.ithttp://www.minkov.it

Table of ContentsTable of Contents1.1. Windows Presentation Foundation Windows Presentation Foundation

(WPF)?(WPF)?

2.2. WPF basic featuresWPF basic features

3.3. WPF and other UI technologiesWPF and other UI technologies Windows Forms Windows Forms DirectXDirectX Silverlight Silverlight HTMLHTML ++ CSCSSS

4.4. WPF classesWPF classes

5.5. XAML basicsXAML basics2

What is Windows What is Windows Presentation Presentation Foundation?Foundation?

What is Windows What is Windows Presentation Presentation Foundation?Foundation?

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) An entirely new graphical display system An entirely new graphical display system

for Windowsfor Windows Empowers rich-media applicationsEmpowers rich-media applications Provides a clear separation between the Provides a clear separation between the

UI (XAML) and the business logic UI (XAML) and the business logic (C#,VB.NET)(C#,VB.NET)

Influenced by modern display Influenced by modern display technologies such as technologies such as HTMLHTML, , CSSCSS and and FlashFlash

Hardware-acceleratedHardware-accelerated

4

WPF WPF BBasic asic FFeatureseatures

VVector ector GGraphics raphics All WPF graphics are All WPF graphics are Direct3DDirect3D

applicationsapplications Direct3DDirect3D (part of DirectX) is used in (part of DirectX) is used in

graphical applications where performance graphical applications where performance is importantis important

Uses the video card hardware for renderingUses the video card hardware for rendering The result: high-quality rich-media UIThe result: high-quality rich-media UI

Vector-based graphics allows to scale Vector-based graphics allows to scale without loss of qualitywithout loss of quality

WPF implements a floating-point logical WPF implements a floating-point logical pixel system and supports 32-bit ARGB pixel system and supports 32-bit ARGB colorcolor

6

RRich ich TText ext MModel odel WPF includes a number of extremely WPF includes a number of extremely

rich typographic and text rendering rich typographic and text rendering featuresfeatures Some of themSome of them were not available in were not available in GDIGDI

BBuilding international fonts from uilding international fonts from composite fontscomposite fonts

WPF text rendering takes advantage of WPF text rendering takes advantage of ClearTypeClearType technology technology Use caching of pre-rendered text in the Use caching of pre-rendered text in the

video memory video memory WPF has resolution-independent WPF has resolution-independent

architecturearchitecture 7

AAnimation nimation WFP supports time-based animationsWFP supports time-based animations

Presentation timers are initialized and Presentation timers are initialized and managed by WPFmanaged by WPF

Scene changes coordinated by using a Scene changes coordinated by using a storyboardstoryboard

Animations can be triggeredAnimations can be triggered By other external eventsBy other external events

Including user actionIncluding user action

Animation can be defined on a per-Animation can be defined on a per-object basis directly from the XAML object basis directly from the XAML markup markup

8

AAudio and udio and VVideo ideo SSupport upport

WPF can incorporate audio and video WPF can incorporate audio and video into a user interfaceinto a user interface

Audio support in WPF is a thin layer over Audio support in WPF is a thin layer over the existing functionality in Win32 and the existing functionality in Win32 and WMPWMP

WPF supports the video in formats WPF supports the video in formats WMV, WMV, MPEGMPEG and some and some AVI AVI files files

Relationship between video and Relationship between video and animation is also supportedanimation is also supported They are both ways of showing moving They are both ways of showing moving

imagesimages Animation can be synchronized with mediaAnimation can be synchronized with media

9

SStyles and tyles and TTemplates emplates In WPF a In WPF a stylestyle is a set of properties is a set of properties

applied to content used for visual applied to content used for visual renderingrendering Similar to the concept of CSSSimilar to the concept of CSS E.g. setting the font weight of a E.g. setting the font weight of a ButtonButton

controlcontrol Use them to standardize Use them to standardize non-non-

formattingformatting characteristics characteristics WPF styles have specific features for WPF styles have specific features for

building applicationsbuilding applications Ability to apply different visual effects Ability to apply different visual effects

based on user eventsbased on user events 10

SStyles and tyles and TTemplates emplates (2)(2)

TTemplatesemplates in WPF allow you to in WPF allow you to fully change the UI of anything in fully change the UI of anything in WPFWPF

KKinds of inds of ttemplates available within emplates available within WPFWPF ControlTemplateControlTemplate ItemsPanelTemplateItemsPanelTemplate DataTemplateDataTemplate HierarchicalDataTemplateHierarchicalDataTemplate

11

CCommands ommands CommandsCommands are more abstract and are more abstract and

loosely-coupled version of eventsloosely-coupled version of events Examples: copy, cut, paste, save, etc.Examples: copy, cut, paste, save, etc.

WPF support for commands reduces WPF support for commands reduces the amount of code we need to the amount of code we need to writewrite

It gives us more flexibility to change It gives us more flexibility to change the UI without breaking the back-the UI without breaking the back-end logicend logic

Commands have action, source, Commands have action, source, target and bindingtarget and binding 12

CCommands ommands (2)(2) The power of commands comes from The power of commands comes from

the following three featuresthe following three features WPF defines a number of built-in WPF defines a number of built-in

commandscommands Commands have automatic support for Commands have automatic support for

input actionsinput actions Some WPF controls have built-in Some WPF controls have built-in

behavior tied to various commandsbehavior tied to various commands Commands are intended to do two Commands are intended to do two

things:things: Check whether an action is availableCheck whether an action is available Execute an actionExecute an action 13

DDeclarative UI with eclarative UI with XAML XAML

WPF introduces a new XML-based WPF introduces a new XML-based language for describing UI elements language for describing UI elements known as known as XAMLXAML XAMLXAML = = eXtensible Application Markup eXtensible Application Markup

LanguageLanguage XAML is a completely declarative XAML is a completely declarative

languagelanguage A declarative language says "what"A declarative language says "what" An imperative language says "how"An imperative language says "how"

XAML describes the behavior and XAML describes the behavior and integration of components (in most integration of components (in most cases UI components)cases UI components) 14

OObject-bject-BBased ased DDrawing rawing At the lower-level WPF works in terms of At the lower-level WPF works in terms of

shapesshapes, not in terms of painting pixels, not in terms of painting pixels ShapesShapes are vector-based and can easily are vector-based and can easily

scalescale Developers create Developers create shapeshape objects and let objects and let

WPF maintain the display in the most WPF maintain the display in the most optimized wayoptimized way WPF provides a number of ready-to-use WPF provides a number of ready-to-use

shape objects like line, rectangle, ellipse, shape objects like line, rectangle, ellipse, path, etc.path, etc.

Shape objects can be used inside panels Shape objects can be used inside panels and inside most WPF controlsand inside most WPF controls

15

WPF WPF aand nd OOther UI ther UI TTechnologiesechnologies

Windows FormsWindows Forms

Windows Forms is the culmination of Windows Forms is the culmination of the display technology built on GDI+ the display technology built on GDI+ and User32and User32 It’s more mature than WPFIt’s more mature than WPF Has solid limitationsHas solid limitations No separation between UI and the C# No separation between UI and the C#

codecode WPF is the platform for the future of WPF is the platform for the future of

Windows developmentWindows development Based on DirectX and Direct3DBased on DirectX and Direct3D Separation between the UI and C# codeSeparation between the UI and C# code 17

DirectXDirectX WPF create multimedia applications WPF create multimedia applications

with real-time graphicswith real-time graphics Such as complex physics-based Such as complex physics-based

simulators or cutting-edge action gamessimulators or cutting-edge action games WPF applicationsWPF applications are are DirectX DirectX

applicationsapplications As a result, even the most mundane As a result, even the most mundane

business applications can use rich business applications can use rich effects and effects and antialiasingantialiasing

WPF graphics is entirely vector-basedWPF graphics is entirely vector-based This allows zoom-in / soom-out with no This allows zoom-in / soom-out with no

loss of qualityloss of quality 18

SilverlightSilverlight SilverlightSilverlight is a cross-platform, cross- is a cross-platform, cross-

browser plugin, which contains WPF-browser plugin, which contains WPF-based technologybased technology Rich Internet Application (RIA) platformRich Internet Application (RIA) platform Including XAML and subset of WPFIncluding XAML and subset of WPF Provides rich-media features such as Provides rich-media features such as

video, vector graphics, and animationsvideo, vector graphics, and animations Silverlight and WPF share the XAML Silverlight and WPF share the XAML

presentation layerpresentation layer Both technologies are similar, but Both technologies are similar, but

Silverlight is limited in many aspectsSilverlight is limited in many aspects19

HTMLHTML ++ CSSCSS vs. XAML + vs. XAML + StylesStyles

Cascading Style Sheets (CSS) is a Cascading Style Sheets (CSS) is a stylesheetstylesheet language language Used to describe the presentation of Used to describe the presentation of

information in HTML documentsinformation in HTML documents XAML elements have XAML elements have StyleStyle property property

Similar to CSS (as a concept)Similar to CSS (as a concept) The HTML and XAML are tag based The HTML and XAML are tag based

systems to describe UIsystems to describe UI XAML is more powerful in many XAML is more powerful in many

aspectsaspects20

XAML BasicsXAML Basics

XAML BasicsXAML Basics XAML is an XML-based language for XAML is an XML-based language for

creating and initializing .NET objectscreating and initializing .NET objects It’s used in WPF as a It’s used in WPF as a human-human-

authorableauthorable way of describing the UI way of describing the UI Used to separate the UI from the C# Used to separate the UI from the C#

codecode XAML contains a hierarchy of XAML contains a hierarchy of

elements representing visual objectselements representing visual objects These objects are known as user These objects are known as user

interface elements or UI elementsinterface elements or UI elements

22

Elements and Elements and AttributesAttributes

UI elements have a set of common UI elements have a set of common properties and functionsproperties and functions Such as Such as WidthWidth, , HeightHeight, , CursorCursor, and , and TagTag

propertiesproperties Declaring an XML element in XAMLDeclaring an XML element in XAML

Equivalent to instantiating the object Equivalent to instantiating the object via a via a parameterlessparameterless constructor constructor

Setting an attribute on the object Setting an attribute on the object elementelement Equivalent to setting a property of the Equivalent to setting a property of the

same namesame name23

XAML Basics - ExampleXAML Basics - Example

Constructs button with caption Constructs button with caption "OK""OK"

24

<Window x:Class="MyFirstWpfApp.MainWindow" xmlns=<Window x:Class="MyFirstWpfApp.MainWindow" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presenta"http://schemas.microsoft.com/winfx/2006/xaml/presentation" tion" xmlns:x=xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml Title="Hello, WPF" Height="300" Width="300">Title="Hello, WPF" Height="300" Width="300"> <Button x:Name="button"<Button x:Name="button" Width="200"Width="200" Height="25">OK</Button>Height="25">OK</Button></Window></Window>

Example – EExample – Explanationxplanation

The root element, The root element, WindowWindow is used to is used to declare a portion of a classdeclare a portion of a class

The two XML namespace The two XML namespace declarations pull in two commonly declarations pull in two commonly used namespacesused namespaces The one for XAML itselfThe one for XAML itself The one for WPFThe one for WPF

WidthWidth, , HeightHeight, , TitleTitle are the XAML are the XAML propertiesproperties

25

XAML SyntaxXAML SyntaxLive DemoLive Demo

What is XAML?What is XAML?

What is XAML?What is XAML? eeXXtensible tensible AApplication pplication MMarkup arkup LLanguageanguage XAML is a declarative markup languageXAML is a declarative markup language

Used to simplify creation of UI for a .NET Used to simplify creation of UI for a .NET apps apps

Separates UI and Business logicSeparates UI and Business logic XAML enables a workflow where XAML enables a workflow where

different parties can work different parties can work simultaneouslysimultaneously The UI and the logic of an application can The UI and the logic of an application can

be developed using different tools (VS be developed using different tools (VS and Blend)and Blend)

What is XAML? (2)What is XAML? (2) XAML is an XML-based language for XAML is an XML-based language for

creating and initializing .NET objectscreating and initializing .NET objects It’s used in WPF and Silverlight as a It’s used in WPF and Silverlight as a

human-authorablehuman-authorable way of describing way of describing the UIthe UI

Used to separate the UI from the C# Used to separate the UI from the C# codecode

XAML contains a hierarchy of XAML contains a hierarchy of elements representing visual objectselements representing visual objects These objects are known as user These objects are known as user

interface elements or UI elementsinterface elements or UI elements29

DDeclarative UI with eclarative UI with XAML XAML

XAML introduces a new XML-based XAML introduces a new XML-based language for describing UI elements language for describing UI elements known as known as XAMLXAML XAMLXAML = = eXtensible Application Markup eXtensible Application Markup

LanguageLanguage XAML is a completely declarative XAML is a completely declarative

languagelanguage A declarative language says "what"A declarative language says "what" An imperative language says "how"An imperative language says "how"

XAML describes the behavior and XAML describes the behavior and integration of components (in most integration of components (in most cases UI components)cases UI components) 30

Property Property ElementsElements

Property ElementsProperty Elements Not all properties have just a string Not all properties have just a string

valuevalue Some must be set to an instance of Some must be set to an instance of

an objectan object XAML provide syntax for setting XAML provide syntax for setting

complex property values, called complex property values, called property elementsproperty elements Take the form Take the form TypeName.PropertyName TypeName.PropertyName contained contained inside an inside an TypeNameTypeName elementelement

32

<Ellipse><Ellipse> <Ellipse.RenderTransform><Ellipse.RenderTransform> <RotateTransform Angle="45" <RotateTransform Angle="45" CenterY="60" />CenterY="60" /> </Ellipse.RenderTransform></Ellipse.RenderTransform></Ellipse></Ellipse>

A property A property elementelement

Property ElementsProperty ElementsLive DemoLive Demo

Declarative vs. Declarative vs. Programmatically?Programmatically?

Why we need XAML?Why we need XAML?

Declarative vs. Declarative vs. ProgrammaticallyProgrammatically

In WPF/Silverlight each element In WPF/Silverlight each element can be done either declaratively or can be done either declaratively or programmaticallyprogrammatically No difference in the execution and No difference in the execution and

speedspeed

Instantiating element from the code Instantiating element from the code behind ruins the idea of XAMLbehind ruins the idea of XAML

The same as Windows FormsThe same as Windows Forms

The following two examples are The following two examples are identicalidentical<Button Content="Click <Button Content="Click me!"/>me!"/>

Button button=new Button();Button button=new Button();button.Content="Click me!";button.Content="Click me!";

With With XAMLXAML

From Code From Code BehindBehind

Declarative UIDeclarative UI When not using XAML with When not using XAML with

WPF/SilverlightWPF/Silverlight Miss the idea of separation of concernsMiss the idea of separation of concerns

Two parties cannot work Two parties cannot work simultaneously on the same filesimultaneously on the same file

What happens when making object What happens when making object declaratively?declaratively? It is the same as instantiating the It is the same as instantiating the

element with parameterless constructorelement with parameterless constructor

All the magic happens in All the magic happens in InitializeComponents()InitializeComponents()

WPF vs. Windows WPF vs. Windows FormsForms

Windows FormsWindows Forms Framework to design applications with GUIFramework to design applications with GUI Does the same job as WPFDoes the same job as WPF Everything is in one placeEverything is in one place Much like java's swings (by concept)Much like java's swings (by concept)

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) Separate UI and Business LogicSeparate UI and Business Logic

Why change the concept of the UI?Why change the concept of the UI? In Windows Forms all the code is in one In Windows Forms all the code is in one

placeplace Harder for front-end and back-end Harder for front-end and back-end

developersdevelopers

Declarative or Declarative or Programmatically?Programmatically?

Live DemoLive Demo

QuestionsQuestions??

Introduction to XAMLIntroduction to XAML

Recommended