Download - Learn Enterprise WPF with XAML from Scratch
Elias Fofanov
http://engineerspock.com
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
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?
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
WPF Architecture
Video driver
Composition Engine (MIL)
PresentationCore.dll
PresentationFramework.dll
DirectX
WindowBase.dllManaged
Unmanaged
Kernel
The Future of WPFPerformance
Modern Hardware
Tooling
Bugs-Fixing
DirectX Integration
.NET & WPF
WPF Tools
Interactive tool which provides reach experience of creating sophisticated designs and layouts.
Provides reach coding and debugging experience .
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
Basics of UI-Development
• DPI (dots per inch), PPI (pixels per inch)
• Pixel• Raster Graphics and Vector Graphics• Independent Pixel ;
• Aspect Ratio• ClearType rendering
Text Rendering
• TextOptions.TextFormattingMode can be set to Ideal or Display• TextOptions.TextRenderingMode can be set to Auto, Aliased, Grayscale, ClearType.
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
Elias Fofanov
http://engineerspock.com
Controls
Outline
• Buttons• Containers with Headers• Range Controls• Items Controls• Text Input• Images and Menu Controls
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
ButtonsFrameworkElement
Control
ContentControl
ButtonBase
Button ToggleButton
RepeatButton CheckBox RadioButton
Headered Content ControlsFrameworkElement
Control
ContentControl
HeaderedContentControl
Expander GroupBox
Content property
Header property
Range ControlsFrameworkElement
Control
RangeBase
Slider ProgressBar
Brings properties:• Value• Minimum• Maximum• SmallChange• LargeChange• Orientation
ScrollBar
Items ControlsFrameworkElement
Control
ComboBox
ItemsControl
ListBox TabControl TreeView
Brings properties:• Items (readonly)• ItemsSource• DisplayMemberPath• ItemsPanel• ItemTemplate
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
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
Summary
• Controls and Primitive Elements• Buttons• Headered Content Controls• Range Controls• Items Controls• TextBox, TextBlock, Label• Menu Controls
Elias Fofanov
http://engineerspock.com
Layout
Outline• Layout Core Types• Layout Process• Sizing Elements• Positioning Elements• ViewBox• Panels: StackPanel, WrapPanel, DockPanel, Grid
Layout Core Types
• UIElement exposes Measure and Arrange methods• FrameworkElement exposes Height, Width, HorizontalAlignment,
VerticalAlignment• Panel is the base class for all panels
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
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
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
ViewBox
ViewBox can scale its inner Content.
FrameworkElement
Decorator
ViewBox
Exposes two Properties: • Stretch• StretchDirection
None, Fill, Uniform, UniformToFillBoth, DownOnly, UpOnly
default
default
Panel
Panels compose UI-elements together.
UIElement
FrameworkElement
Panel
Panel exposes: • UIElementCollection Children
Panels: Canvas, StackPanel, WrapPanel, DockPanel and Grid
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>
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
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
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
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
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
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
Elias Fofanov
http://engineerspock.com
WPF Properties and Events
Outline
• DependencyProperty, AttachedProperty• Events: Bubbling, Tunneling, Direct
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
Dependency Properties
• Property Value Inheritance• Change Notifications• Data Binding• Value Provider’s Precedence• Default Values• Animation• Styling
Features:
Calculating the Value of a Dependency Property
Determine Base Value
Evaluate in case of Expression Apply Animations Coerce Validate
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));
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
Elias Fofanov
http://engineerspock.com
Data Binding
Outline
• The target of a binding should be a DependencyProperty• Any object you like could be the
source of data.
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
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
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
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.
Asynchronous Bindings
Binding works with data in the UI-thread by default
To make binding asynchronous just set IsAsync = true
Summary
• Binding properties• What is a source object and how to set it for a binding• INotifyPropertyChanged• ObservableCollection• Converters• Asynchronous Binding
Elias Fofanov
http://engineerspock.com
Resources
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
Binary Resources
• Content – loose resource on a disk• EmbeddedResource – embed in assembly• Resource – embed in assembly, but with extended WPF support
Logical Resources
public ResourceDictionary Resources { get; set; }
WPF implements a lazy initialization of resources
FrameworkElement and FrameworkContentElement:
Static and Dynamic Resources
• StaticResource applies once• DynamicResource applies each time a resource is updated• StaticResource has a slightly better performance
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.
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
Summary• Binary and Logical resources• WPF supports Dictionaries intrinsically• StaticResource and DynamicResource extensions• Resources Lookup• How to organize dictionaries and merge them
Elias Fofanov
http://engineerspock.com
User Controls and Custom Controls
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.
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
Elias Fofanov
http://engineerspock.com
Styles, Triggers, Templates, Skins
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
Styles
• Styles are based on resource system• Styles gather together property values• Styles can be applied multiple times
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
Templates
• WPF Controls look is based on templates• Default Templates are defined by OS themes• Template defines a key and a target type
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
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
Elias Fofanov
http://engineerspock.com
WPF Application Model
Application StartupApplication.Run()
Initialized Activated Activated LoadedStartup
ContentRendered
Window is VisibleAnimation, styles, bindings applied
Application Window Application Window Window
Window
Application Shutdown
Closing Deactivated ExitClosed
Window ApplicationWindow Window
Deactivated
Application
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?
”
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
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
Summary
• Start and Shutdown events sequence• Threading Model• Global exceptions handling