learn enterprise wpf with xaml from scratch

77
Elias Fofanov http://engineerspock.com Learn Enterprise WPF with XAML from Scratch

Upload: elias-fofanov

Post on 16-Apr-2017

499 views

Category:

Education


16 download

TRANSCRIPT

Page 1: Learn Enterprise WPF with XAML from Scratch

Elias Fofanov

http://engineerspock.com

Learn Enterprise WPF with XAML from Scratch

Page 2: Learn Enterprise WPF with XAML from Scratch

Course OutlineThis course covers:1. Controls2. Layout3. Properties and Events4. Data Binding5. Resources6. Styles, Triggers, Templates, Skins7. User Controls and Custom Controls8. Application Model

Page 3: Learn Enterprise WPF with XAML from Scratch

Introduction OutlineYou will be able to answer the following questions:1. Why you should choose WPF as a UI-

development platform?2. What is the actual status of the WPF-

platform? Is it alive?3. What tools supporting WPF exist and

what’s their status?4. How the WPF-architecture is organized?5. What are the basic notions of UI-

development, which every UI-developer should be aware of?

Page 4: Learn Enterprise WPF with XAML from Scratch

Why WPF?

Windows Forms1. Rendering based on GDI and GDI+

2. Lack of hardware acceleration support

3. Hard to use for hardware animation

4. Unable to harness the power of modern graphics cards

WPF1. Integrated

2. Resolution Independence

3. Separation of programming and designing concerns

4. Infinite possibilities of customization

5. Simplicity of styling

Page 5: Learn Enterprise WPF with XAML from Scratch

WPF Architecture

Video driver

Composition Engine (MIL)

PresentationCore.dll

PresentationFramework.dll

DirectX

WindowBase.dllManaged

Unmanaged

Kernel

Page 6: Learn Enterprise WPF with XAML from Scratch

The Future of WPFPerformance

Modern Hardware

Tooling

Bugs-Fixing

DirectX Integration

Page 7: Learn Enterprise WPF with XAML from Scratch

.NET & WPF

Page 8: Learn Enterprise WPF with XAML from Scratch

WPF Tools

Interactive tool which provides reach experience of creating sophisticated designs and layouts.

Provides reach coding and debugging experience .

Page 9: Learn Enterprise WPF with XAML from Scratch

WPF Tools Recent Improvements

• New performance tool - Timeline

• Improved debugging of bindings and visual trees

• Consistent look and feel with Visual Studio

• Powerful Solution Explorer

• Powerful IntelliSense

• Enhanced navigation through the XAML-code

• Several improvements reduce the number of switches between Blend and Visual Studio

Page 10: Learn Enterprise WPF with XAML from Scratch

Basics of UI-Development

• DPI (dots per inch), PPI (pixels per inch)

• Pixel• Raster Graphics and Vector Graphics• Independent Pixel ;

• Aspect Ratio• ClearType rendering

Page 11: Learn Enterprise WPF with XAML from Scratch

Text Rendering

• TextOptions.TextFormattingMode can be set to Ideal or Display• TextOptions.TextRenderingMode can be set to Auto, Aliased, Grayscale, ClearType.

Page 12: Learn Enterprise WPF with XAML from Scratch

Summary

• WPF is a preferable technology of building Windows UI-applications• WPF has a future as a part of the .NET-platform• Blend and Visual studio are the great tools supporting WPF• Now you have a grip on basics of UI-development• You were introduced to XAML-basics and how it works

Page 13: Learn Enterprise WPF with XAML from Scratch

Elias Fofanov

http://engineerspock.com

Controls

Page 14: Learn Enterprise WPF with XAML from Scratch

Outline

• Buttons• Containers with Headers• Range Controls• Items Controls• Text Input• Images and Menu Controls

Page 15: Learn Enterprise WPF with XAML from Scratch

Class HierarchyObjectDispatcherObject

DependencyObject

Visual

UIElement

FrameworkElement

ContentPresenter Control Panel Shape

ContentControl

ToggleButton

Label

Button

ComboBox

ItemsControl

ListBox

Shape

Canvas

StackPanel

Grid

WrapPanel

Rectangle

Ellipse

Path

Line

Page 16: Learn Enterprise WPF with XAML from Scratch

ButtonsFrameworkElement

Control

ContentControl

ButtonBase

Button ToggleButton

RepeatButton CheckBox RadioButton

Page 17: Learn Enterprise WPF with XAML from Scratch

Headered Content ControlsFrameworkElement

Control

ContentControl

HeaderedContentControl

Expander GroupBox

Content property

Header property

Page 18: Learn Enterprise WPF with XAML from Scratch

Range ControlsFrameworkElement

Control

RangeBase

Slider ProgressBar

Brings properties:• Value• Minimum• Maximum• SmallChange• LargeChange• Orientation

ScrollBar

Page 19: Learn Enterprise WPF with XAML from Scratch

Items ControlsFrameworkElement

Control

ComboBox

ItemsControl

ListBox TabControl TreeView

Brings properties:• Items (readonly)• ItemsSource• DisplayMemberPath• ItemsPanel• ItemTemplate

Page 20: Learn Enterprise WPF with XAML from Scratch

Selectors

Selector exposes: • SelectedItem• SelectedIndex• SelectedValue• SelectedValuePath

Selectors allow to select indexed items.

ItemsControl

Selector

void SelectionChangedEventHandler(object sender, SelectionChangedEventArgs e);

Selector exposes SelectionChanged event of signature:

SelectionChangedEventArgs exposes: • IList AddedItems• IList RemovedItems

Page 21: Learn Enterprise WPF with XAML from Scratch

Image

Selector exposes: • Source• ImageSource• Stretch• StretchDirection

Image is a control for hosting images.

Rendering quality is controlled via the RenderingOptions.BitmapScalingMode: Fant, HighQuality, Linear, LowQuality, NearestNeighbor

None, Fill, Uniform, UniformToFillBoth, DownOnly, UpOnly

default

default

Page 22: Learn Enterprise WPF with XAML from Scratch

Summary

• Controls and Primitive Elements• Buttons• Headered Content Controls• Range Controls• Items Controls• TextBox, TextBlock, Label• Menu Controls

Page 23: Learn Enterprise WPF with XAML from Scratch

Elias Fofanov

http://engineerspock.com

Layout

Page 24: Learn Enterprise WPF with XAML from Scratch

Outline• Layout Core Types• Layout Process• Sizing Elements• Positioning Elements• ViewBox• Panels: StackPanel, WrapPanel, DockPanel, Grid

Page 25: Learn Enterprise WPF with XAML from Scratch

Layout Core Types

• UIElement exposes Measure and Arrange methods• FrameworkElement exposes Height, Width, HorizontalAlignment,

VerticalAlignment• Panel is the base class for all panels

Page 26: Learn Enterprise WPF with XAML from Scratch

Layout Process

• Step 1. Each UI-element determines its DesiredSizeEach element asks its children (by calling the Measure method on each child) how much space do they want to encompass.

• Step 2. Assign sizes and positions Elements recursively call on their children the Arrange method passing the size allocated for each child and the position from which the child can arrange itself.

Layout process consists of two steps: • Measure • Arrange

Page 27: Learn Enterprise WPF with XAML from Scratch

Sizing UI ElementsFrameworkElement: • Width, Height• MinWidth, MinHeight

double.NaN by default

• Thickness Margin

Thickness Control.Padding – margin between external control’s boundaries and its internal content

Visibility UIElement.Visibility Visible, Collapsed, Hidden

Page 28: Learn Enterprise WPF with XAML from Scratch

Positioning UI Elements

Alignments have an impact on the layout only when the DesiredSize of a control is less than the available size for its rendering.

FrameworkElement: • VerticalAlignment• HorizontalAlignment

Top, Center, Bottom, Stretch

Control: • VerticalContentAlignment• HorizontalContentAlignment

Left, Right, Center, Stretch

Page 29: Learn Enterprise WPF with XAML from Scratch

ViewBox

ViewBox can scale its inner Content.

FrameworkElement

Decorator

ViewBox

Exposes two Properties: • Stretch• StretchDirection

None, Fill, Uniform, UniformToFillBoth, DownOnly, UpOnly

default

default

Page 30: Learn Enterprise WPF with XAML from Scratch

Panel

Panels compose UI-elements together.

UIElement

FrameworkElement

Panel

Panel exposes: • UIElementCollection Children

Panels: Canvas, StackPanel, WrapPanel, DockPanel and Grid

Page 31: Learn Enterprise WPF with XAML from Scratch

CanvasCanvas allows to use absolute positioning of its child UI-elements.

<Canvas> <Rectangle Canvas.Left="12" Canvas.Top="12" Fill="Red"/> <Rectangle Canvas.Left="12" Canvas.Bottom="12" Fill="Black"/> <Rectangle Canvas.Right="12" Canvas.Top="12" Fill="Blue"/> <Rectangle Canvas.Right="12" Canvas.Bottom="12" Panel.ZIndex="1" Fill="BlueViolet"/> <Rectangle Canvas.Right="64" Canvas.Bottom="120" Panel.ZIndex="2" Fill="Chartreuse"/> </Canvas>

Page 32: Learn Enterprise WPF with XAML from Scratch

StackPanel

StackPanel allows to arrange UI-elements in stacks.

Exposes: • Orientation Horizontal, Vertical

default

• Vertical StackPanel allows to align children Horizontally• Horizontal StackPanel allows to align children Vertically

Page 33: Learn Enterprise WPF with XAML from Scratch

WrapPanelWrapPanel allows to arrange UI-elements in stacks wrapping them in case of overflow.

• Vertical WrapPanel adds a column when children overflow panel’s height• Horizontal WrapPanel adds a row when children overflow panel’s width

Exposes: • Orientation• ItemWidth• ItemHeight

Horizontal, Vertical

default

Uniform sizes

Page 34: Learn Enterprise WPF with XAML from Scratch

DockPanelDockPanel allows to arrange UI-elements by docking them to borders.

• Last child fills the remaining space unless LastChildFill is set to false• If LastChildFill is set to true, then the last child’s Dock value is ignored

Exposes: • Dock• LastChildFill

Left, Right, Bottom, TopTrue\False

default

Page 35: Learn Enterprise WPF with XAML from Scratch

GridGrid allows to arrange UI-elements in rows and columns.

Exposes: • RowDefinitions• ColumnDefinitions

Used for defining rows and columns

To position children inside a Grid: • Grid.Row, Grid.Column• Grid.RowSpan, Grid.ColumnSpan

Page 36: Learn Enterprise WPF with XAML from Scratch

GridRowDefinition and ColumnDefinition: • GridLength Height, Width• double MinHeight, MinWidth

GridLength can be set to:

<Grid ShowGridLines="True"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="100"/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="3*"/> <ColumnDefinition Width="4*"/> <ColumnDefinition Width="5*"/> </Grid.ColumnDefinitions> <Rectangle Fill="Red" Height="120"/> <Rectangle Grid.Row="0" Grid.Column="1" Fill="Aqua" Height="120"/> <Rectangle Grid.Row="0" Grid.Column="2" Grid.RowSpan="2" Fill="Yellow"/> <Rectangle Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Fill="Blue"/> <Rectangle Grid.Row="2" Grid.Column="2" Fill="Brown"/> </Grid>

Points

<RowDefinition Height="100"/>

Height is Fixed

Auto

<RowDefinition Height=“Auto"/>

Height is determined by the Highest Child

Star

<ColumnDefinition Width="3*"/>

Width value is relative

Page 37: Learn Enterprise WPF with XAML from Scratch

Summary

• Important Types: UIElement, FrameworkElement, Panel• Layout Process: Measure and Arrange• Sizing: Height, Width, MinHeight, MinWidth, MaxHeight, MaxWidth,

Margin, Padding, Visibility• Positioning: VerticalAlignment, HorizontalAlignment,

VerticalContentAlignment, HorizontalContentAlignment• Panels: Canvas, StackPanel, WrapPanel, DockPanel, Grid

Page 38: Learn Enterprise WPF with XAML from Scratch

Elias Fofanov

http://engineerspock.com

WPF Properties and Events

Page 39: Learn Enterprise WPF with XAML from Scratch

Outline

• DependencyProperty, AttachedProperty• Events: Bubbling, Tunneling, Direct

Page 40: Learn Enterprise WPF with XAML from Scratch

Dependency Properties• Ordinary .NET properties

wrap Dependency Properties

Attached Property can be attached to any object you like.

public class Element : DependencyObject { public static readonly DependencyProperty SecurityIdProperty = DependencyProperty.RegisterAttached("SecurityId", typeof (string), typeof (Element), new PropertyMetadata("")); public static string GetSecurityId(DependencyObject d) { return (string) d.GetValue(SecurityIdProperty); }  public static void SetSecurityId(DependencyObject d, string value) { d.SetValue(SecurityIdProperty, value); }  public static readonly DependencyProperty SizeProperty = DependencyProperty.Register("Size", typeof (Size), typeof (Element), new UIPropertyMetadata(new Size(0, 0)));  public Size Size { get { return (Size) GetValue(SizeProperty); } set { SetValue(SizeProperty, value); } } }

• Stored in optimized pool

Page 41: Learn Enterprise WPF with XAML from Scratch

Dependency Properties

• Property Value Inheritance• Change Notifications• Data Binding• Value Provider’s Precedence• Default Values• Animation• Styling

Features:

Page 42: Learn Enterprise WPF with XAML from Scratch

Calculating the Value of a Dependency Property

Determine Base Value

Evaluate in case of Expression Apply Animations Coerce Validate

Page 43: Learn Enterprise WPF with XAML from Scratch

Routed Events

• Tunneling – PreviewMouseDown, PreviewMouseUp Window->Panel->Rectangle• Bubbling – MouseDown, MouseUp, Click Rectangle->Panel->Window• Direct - MouseEnter public static readonly RoutedEvent MouseDownEvent =

EventManager.RegisterRoutedEvent(

"MouseDown",

RoutingStrategy.Bubble, typeof(MouseButtonEventHandler),

typeof(Mouse));

Page 44: Learn Enterprise WPF with XAML from Scratch

Summary

• Logical and Visual trees may become very deep• DP support many features• Attached property can be attached to any UI-element• DP value providers precedence• Routed Events: bubbling, tunneling, direct

Page 45: Learn Enterprise WPF with XAML from Scratch

Elias Fofanov

http://engineerspock.com

Data Binding

Page 46: Learn Enterprise WPF with XAML from Scratch

Outline

• The target of a binding should be a DependencyProperty• Any object you like could be the

source of data.

Page 47: Learn Enterprise WPF with XAML from Scratch

Outline1. How bindings work?2. How to bind UI-elements to each other?3. What are the binding modes supported?4. Data Context5. Data Templates6. Binding to Collections7. DataGrid8. Converters9. Async Bindings

Page 48: Learn Enterprise WPF with XAML from Scratch

Basics of Data Binding• Source – defines a source object• Path – defines a path to a source property• ElementName – defines a source object in

the Visual Elements Tree• Mode – OneWay, TwoWay, OneWayToSource

Page 49: Learn Enterprise WPF with XAML from Scratch

Source Object• ElementName – defines a source object in the Visual

Elements Tree• RelativeSource – similar to ElementName, but provides

special features for searching UI-elements by some criterion• DataContext – sets a source as a context for many elements• Source – defines a source object by referencing it via the

StaticResource extension

Page 50: Learn Enterprise WPF with XAML from Scratch

ConvertersConverter is a bridge between incompatible types of targets and sources.

IValueConverter:public object Convert(object value, Type targetType, object parameter)public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

Converter can be injected via Binding.Converter property.

Page 51: Learn Enterprise WPF with XAML from Scratch

Asynchronous Bindings

Binding works with data in the UI-thread by default

To make binding asynchronous just set IsAsync = true

Page 52: Learn Enterprise WPF with XAML from Scratch

Summary

• Binding properties• What is a source object and how to set it for a binding• INotifyPropertyChanged• ObservableCollection• Converters• Asynchronous Binding

Page 53: Learn Enterprise WPF with XAML from Scratch

Elias Fofanov

http://engineerspock.com

Resources

Page 54: Learn Enterprise WPF with XAML from Scratch

OutlineBinary and Logical resources

There are three main options you can choose for the build action:• Content• Resource • EmbeddedResource

Ordinary C#-objects are represented by Logical Resources

Page 55: Learn Enterprise WPF with XAML from Scratch

Binary Resources

• Content – loose resource on a disk• EmbeddedResource – embed in assembly• Resource – embed in assembly, but with extended WPF support

Page 56: Learn Enterprise WPF with XAML from Scratch

Logical Resources

public ResourceDictionary Resources { get; set; }

WPF implements a lazy initialization of resources

FrameworkElement and FrameworkContentElement:

Page 57: Learn Enterprise WPF with XAML from Scratch

Static and Dynamic Resources

• StaticResource applies once• DynamicResource applies each time a resource is updated• StaticResource has a slightly better performance

Page 58: Learn Enterprise WPF with XAML from Scratch

Resource LookupLookup Algorithm:• Current element’s resource dictionary • Each parent until reaches the root element• Application scope• Theme• System

If WPF can’t find the resource it throws an InvalidOperationException.

Page 59: Learn Enterprise WPF with XAML from Scratch

Resource Dictionary

• For the sake of ordering resources, you can put resource dictionaries into separate XAML-files

• In order to make such dictionaries visible, you have to merge them at the application scope

Page 60: Learn Enterprise WPF with XAML from Scratch

Summary• Binary and Logical resources• WPF supports Dictionaries intrinsically• StaticResource and DynamicResource extensions• Resources Lookup• How to organize dictionaries and merge them

Page 61: Learn Enterprise WPF with XAML from Scratch

Elias Fofanov

http://engineerspock.com

User Controls and Custom Controls

Page 62: Learn Enterprise WPF with XAML from Scratch

User Control and Custom Control

• User Control is a reusable bunch of controls which are composed somehow and have a logical interconnection between them.• Custom Control is a separate control like a Button or a

ProgressBar. You should create one only in case there is no such a control in WPF out of the box.

Page 63: Learn Enterprise WPF with XAML from Scratch

Summary

• User Control and Custom Control are different concepts• User Control composes existing Controls• Custom Control is either a separate control developed from

the scratch or a control which extends an existing one

Page 64: Learn Enterprise WPF with XAML from Scratch

Elias Fofanov

http://engineerspock.com

Styles, Triggers, Templates, Skins

Page 65: Learn Enterprise WPF with XAML from Scratch

Outline

• Styles enhance the look of WPF applications• Triggers make Styles, Templates and Bindings reactive• Templates help to change the look of controls• Skins allow to change the look of a WPF application on the fly

Page 66: Learn Enterprise WPF with XAML from Scratch

Styles

• Styles are based on resource system• Styles gather together property values• Styles can be applied multiple times

Page 67: Learn Enterprise WPF with XAML from Scratch

Triggers

• Property Trigger - applied when a dependency property becomes equal to an expected value defined in a trigger• Data Trigger - the same as a property trigger, but works with

plain .NET properties• Event Trigger - applied when a specific event is raised

Page 68: Learn Enterprise WPF with XAML from Scratch

Templates

• WPF Controls look is based on templates• Default Templates are defined by OS themes• Template defines a key and a target type

Page 69: Learn Enterprise WPF with XAML from Scratch

Skins

• Skins allow to change the appearance of an application in the runtime• Skins are supported because of powerful

Resource, Style and Template systems in WPF

Page 70: Learn Enterprise WPF with XAML from Scratch

Summary

• What styles are? Powerful mechanism to enhance the look of an application• Styles can be empowered by triggers• There are Property, Data and Event Triggers• Control Template can completely change the look of a control• Skin is a set of styles and templates

Page 71: Learn Enterprise WPF with XAML from Scratch

Elias Fofanov

http://engineerspock.com

WPF Application Model

Page 72: Learn Enterprise WPF with XAML from Scratch

Application StartupApplication.Run()

Initialized Activated Activated LoadedStartup

ContentRendered

Window is VisibleAnimation, styles, bindings applied

Application Window Application Window Window

Window

Page 73: Learn Enterprise WPF with XAML from Scratch

Application Shutdown

Closing Deactivated ExitClosed

Window ApplicationWindow Window

Deactivated

Application

Page 74: Learn Enterprise WPF with XAML from Scratch

Threading Model

“Why I get the InvalidOperationException which says in its details that the calling thread cannot access this object because a different thread owns it?

Page 75: Learn Enterprise WPF with XAML from Scratch

Threading Model• WPF based on STA – single-threaded apartment

• STA means that UI-elements have thread affinity. Thread which creates a UI-element becomes its owner and only the owner thread can access that UI-element directly

• All WPF UI-elements derive from DispatcherObject

Page 76: Learn Enterprise WPF with XAML from Scratch

Global Exceptions Handling• Dispatcher.UnhandledException – catches exceptions for specific UI thread• Application.DispatcherUnhandledException – catches exceptions from the main thread• AppDomain.UnhandledException – catches exceptions from a domain• TaskScheduler.UnobservedTaskException – catches exceptions from tasks

Page 77: Learn Enterprise WPF with XAML from Scratch

Summary

• Start and Shutdown events sequence• Threading Model• Global exceptions handling