Upload
others
View
34
Download
2
Embed Size (px)
Citation preview
XAML forWPF and UWP
■ Programming WPF/UWP application with XAML and C#
■ The structure and purpose of XAML and C# code (behind)
■ Layouts and Styles in XAML
■ Data Binding and Events
■ MVVM and Commands
2 von 171School of Engineering © K. Rege, ZHAW
WPFBasics
3 von 171School of Engineering © K. Rege, ZHAW
Differences between Forms and WPF
Difference of thinking and execution
WinForms
■ The Forms and UI Objects are the
application
WPF/MVVM
■ The application data objects are in the
center
■ The GUI is merely an access layer tothese objects
■ Separation of Presentation and
Logic/Date by design
© Rachel Lim's Bloghttps://www.tutorialspoint.com/mvvm/mvvm_wpf_data_templates.htm
4 von 171School of Engineering © K. Rege, ZHAW
WPF – Features
■ XAML/WPF has a set of "nice" features
https://www.tutorialspoint.com/wpf/wpf_quick_guide.htm
5 von 171School of Engineering © K. Rege, ZHAW
HelloXAML/WPF
6 von 171School of Engineering © K. Rege, ZHAW
Hello WPF
■ Project Setup with Visual Studio
■ Choose WPF App
7 von 171School of Engineering © K. Rege, ZHAW
… Hello WPF
8 von 171School of Engineering © K. Rege, ZHAW
… Hello WPF
■ Visual Studio generates a set of filesApp.xaml
App.xaml.cs
MainWindow.xaml
MainWindow.xaml.cs
■ The two App.* files contain the code for
the setup (resources) and start of theapplication
■ The two MainWindow.* files contain the
code for the main window of the
application
9 von 171School of Engineering © K. Rege, ZHAW
Involved Files in Overview and Context
FirstWPF.exeFirstWPF.exe
class Appclass App
App.g.csApp.g.cs MainWindow.Baml
MainWindow.Baml
MainWindow.g.i.cs
MainWindow.g.i.cs
App.xamlApp.xaml App.xaml.cs
App.xaml.cs
MainWindow.xaml
MainWindow.xaml
MainWindow.xaml.cs
MainWindow.xaml.cs
classMainWindow
classMainWindow
10 von 171School of Engineering © K. Rege, ZHAW
Content of the App.xaml.* Files
■ The two files App.xaml App.xaml.cs contain the intialization
■ Start-Window (MainWindow.xaml)
© Dr. Beatrice Amrhein
<Application x:Class="WpfApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApp2" StartupUri="MainWindow.xaml"> <Application.Resources>
</Application.Resources></Application>
namespace WpfApp {
public partial class App : Application {
}}
11 von 171School of Engineering © K. Rege, ZHAW
Content of the generated App.xaml.cs File
■ The Main method is hidden in an also
generated partial class App.xaml.cs
■ should not be modified
class WpfApp : Application {
public static void Main() {
WpfApp.App app = new
WpfApp.App();
app.InitializeComponent();
app.Run();
}
}
■ InitializesComponent() Initialize thecontent of the main window
■ Main() start the application
© Dr. Beatrice Amrhein
12 von 171School of Engineering © K. Rege, ZHAW
Hello XAML
■ The two files MainWindow.xaml MainWindow.xaml.cd contain the main
Window code: enter the Label Hello Word as shown below
<Window x:Class="MainWindow.xaml.cs"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="TestWPF" Height="300" Width="300">
<Grid> <Label> Hallo World
</Label> </Grid></Window>
public partial class MainWindow : Window{public MainWindow (){
InitializeComponent();}
}
13 von 171School of Engineering © K. Rege, ZHAW
The Application Object
14 von 171School of Engineering © K. Rege, ZHAW
The Application Object
■ Every WPF application is represented by an instance ofWindows.UI.Xaml.Application
orWindows.Application
■ A singleton
■ The static property Application.Current returns that instance
■ The Visual Studio wizard creates a XAML file for the application
■ Useful for application level resources
■ Also can set the StartupUri property to indicate which window to show on
startup
© Pavel Yosifovich
15 von 171School of Engineering © K. Rege, ZHAW
… Application Events
■ Startup■ Called after Application.Run is called before the main window is shown■ Can access command line arguments through the StartupEventArgs.Args property■ Can also be used to create a window explicitly (and calling Window.Show) without relying on the
StartupUri property
■ Exit
■ Application is being shutdown (for whatever reason)■ Can set the exit code that is returned to the OS■ Cannot cancel the shutdown process
© Pavel Yosifovich
16 von 171School of Engineering © K. Rege, ZHAW
… Application Events
■ SessionEnding
■ Windows session is ending (e.g. log off or shutdown)
■ Can cancel the shutdown by setting SessionEndingCancelEventArgs.Cancel to true(otherwise WPF calls Application.Shutdown)
■ Activated
■ Occurs when a top level window in the application is activated when the user switches from anotherapplication
■ Also occurs the first time a window is shown
■ Deactivated
■ Occurs when the user switches to another application
© Pavel Yosifovich
17 von 171School of Engineering © K. Rege, ZHAW
… Application Events
■ DispatcherUnhandledException
■ Occurs when an unhandled exception is about to terminate the application■ Only on the current (UI) thread
■ Can be used to log the error, show a nice dialog to the user, etc.■ Can also “cancel” the exception and continue running by setting the property
DispatcherUnhandledExceptionEventArgs.Handled to true
■ Must be careful – difficult to guarantee the application is in a valid state to continue
© Pavel Yosifovich
18 von 171School of Engineering © K. Rege, ZHAW
Application Shutdown
■ Application shutdown is controlled by the ShutdownMode property■ OnLastWindowClose (default) – application shuts down when the last top level window is closed
■ OnMainWindowClose – application shuts down when the main window closes
■ OnExplicitShutdown – the application does not shut down even if all windows are gone
■ Calling Application.Shutdown must be used
■ This call can be used regardless of the setting of the ShutdownMode property
© Pavel Yosifovich
19 von 171School of Engineering © K. Rege, ZHAW
UI Designer and XAML Fundamentals
© Alon Fliess
20 von 171School of Engineering © K. Rege, ZHAW
UI Designer and XAML Fundamentals
■ Visual Studio■ UI Designer
■ Toolbox
■ Document Outline
■ Properties View
■ What is XAML?
■ Basic XAML
■ Type Converters
■ Markup Extensions
■ Naming Elements
■ XAML Rules
■ Summary
© Alon Fliess
21 von 171School of Engineering © K. Rege, ZHAW
Visual Studio
© Alon Fliess
22 von 171School of Engineering © K. Rege, ZHAW
UI Designer
■ Visual Studio UI Designer provides quick
and easy way to produce rich UI
interface
■ Drag and drop UI controls from thetoolbox into the designer
■ The UI designer provides an easy way to
select, resize, align, transform and more,
using only the mouse
■ The UI designer generates XAML andautomatically updated when XAML
changes
© Alon Fliess
23 von 171School of Engineering © K. Rege, ZHAW
Toolbox
■ The toolbox groups UI controls available
at design time
■ 3rd party and custom controls are also
available from the toolbox
■ Simple drag and drop a control from thetoolbox to the designer canvas
■ Element from the toolbox can be also
drag and drop directly into XAML
■ Controls can be searched within the
search box and can be sorted
■ Additional groups can be created
© Alon Fliess
24 von 171School of Engineering © K. Rege, ZHAW
Document Outline
■ The document outline view displays thelogical tree of UI elements, each elementname or type and an icon of theelement’s type
■ Each element in the hierarchy can bedesign-time locked and hidden
■ The document outline is very useful tonavigate between UI elements,especially in complex XAML files
© Alon Fliess
view other windows Document Outline
25 von 171School of Engineering © K. Rege, ZHAW
Properties View
■ The properties view provides an easy arapid way to:
■ Search for an element’s property by its name■ Set simple property value using plain text■ Set complex property value using designers■ Easily select color brushes, styles, font size,
transformations and more■ Register element’s events■ Arrange properties in groups■ Create data bindings■ Reset to default values
© Alon Fliess
26 von 171School of Engineering © K. Rege, ZHAW
What is XAML
© Alon Fliess
27 von 171School of Engineering © K. Rege, ZHAW
What is XAML?
■ XML based language■ Enable separation of UI and behavior (code)
■ XAML allows■ Creation of objects■ Setting of properties■ Connection to events
■ but XAML cannot be executed or call methods directly■ Code behind in C# is used instead
© Alon Fliess
28 von 171School of Engineering © K. Rege, ZHAW
XAML vs. Code
■ Anything that can be done in XAML can be done in code■ But not vice versa
■ XAML is usually shorter and more concise than the equivalent code■ Thanks to type converters and markup extensions
Natural Separation of XAML and Code
■ XAML should be used for initial UI
■ Code will handle events and change items dynamically
© Alon Fliess
29 von 171School of Engineering © K. Rege, ZHAW
Correspondence of XAML and Code
■ Visual Studio UI designer generates XAML on each control
picked from the toolbox
■ XAML can be visually viewed and modified in the UI designer
<Buttonxmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Content="OK" />
Windows.Controls.Button b = newWindows.Controls.Button();()b.Content = "OK";
© Alon Fliess
30 von 171School of Engineering © K. Rege, ZHAW
XAML vs. Code
■ For the GUI specification XAML is usually more readable/shorter than the
corresponding C# code
■ But the result will be the same:
31 von 171School of Engineering © K. Rege, ZHAW
XAML for WPF and UWP
■ The XAML Code looks very similar, but top level element is■ Window for a WPF■ Page for UWP
■ If XAML maps to WPF or UWP classes is defined by the mapping of the XML
Elements to the according library classes
■ For WPF
■ For UWP
using System;using System.Windows;using System.Windows.Controls;
using System;using Windows.ApplicationModel.Activation;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;
© Alon Fliess
32 von 171School of Engineering © K. Rege, ZHAW
XAML Namespaces
■ The default XAML namespace is assigned a value that is mapped to some of theruntime namespaces contain UI elements
■ The “x” namespace is mapped to a special namespace, contains XAML parserspecific types
■ Other XAML namespaces may be mapped to custom namespaces and otherruntime namespaces
■ XAML namespace can be defined on each element level and other customnamespaces can be included
© Alon Fliess
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
default Namespacedefault Namespace
x Namespace all elementswith x: prefix
x Namespace all elementswith x: prefix
33 von 171School of Engineering © K. Rege, ZHAW
Elements and Attributes
■ Elements with type names designate objects, created via the defaultconstructor
■ i.e. Name of the Element correspond to the library class instantiated
■ Attributes indicate property or event values■ Event values are event handlers (methods) names
■ Child elements are used (besides other) for Complex properties using a<Type.Property> notation
Complex PropertyComplex Property
Properties of ButtonProperties of Button
34 von 171School of Engineering © K. Rege, ZHAW
XAML and its Code Behind
■ A root element, usually Page or Window classes, can have code behind file
■ The name of the code behind file is correlated to the XAML file name
■ For example: MainPage.xaml and MainPage.xaml.cs
■ The code behind full class name is specified from XAML using
the x:Class directive
Window for WPFWindow for WPF
© Alon Fliess
35 von 171School of Engineering © K. Rege, ZHAW
Child Elements
Child elements that are not simple Content can be one of
■ A value - often specifiable as Attribute if convertible to String
■ The Complex Content property of the object
■ Collection items
■ The object implements IList or IDictionary
© Alon Fliess
36 von 171School of Engineering © K. Rege, ZHAW
Content Property - A Value
■ A single property that is designated with the ContentProperty attribute on the
type can be specified in different ways
© Alon Fliess
a Value as Childa Value as Child
a Value as Content Attributea Value as Content Attribute
Content Property as ChildContent Property as Child Content Property as ChildContent Property as Child
37 von 171School of Engineering © K. Rege, ZHAW
Collection Items
■ List (IList)
■ Dictionary (IDictionary)
© Alon Fliess
38 von 171School of Engineering © K. Rege, ZHAW
Summary of XAML Rules
■ XML Element – create a new instance
■ XML attribute – set a property (as String) or register an event■ ContentProperty attribute for simple properties that are strings<Button content = "Hallo" />
■ Type.Property – set a “complex” property<Button>
<Button.Content>
<Rectangle Fill="Blue" />
</Button.Content>
</Button>
■ Complex Property of type IList or IDictionary
■ Add child elements (XAML calls appropriate Add method)■ Need a x:Key in case of a dictionary
© Alon Fliess
39 von 171School of Engineering © K. Rege, ZHAW
Parsing and Using XAML
© Alon Fliess
40 von 171School of Engineering © K. Rege, ZHAW
Parsing and Using XAML
■ Visual Studio compiles the XAML file to BAML (Binary XAML) and embeds it as
a resource
■ The BAML is parsed at runtime and the object tree created by the generatedInitializeComponent method
© Alon Fliess
41 von 171School of Engineering © K. Rege, ZHAW
Naming Elements and Code Behind
■ Elements can be named using the x:Name XAML attribute
■ The code-behind file will contain a field with that name
■ e.g. A Label defined with x:Name "label1" can be referenced in the code-
behind as follows
© Alon Fliess
42 von 171School of Engineering © K. Rege, ZHAW
XAML Keywords of x Namespace
Keyword Valid on Meaning
x:Class Root element The code behind class that derivesfrom the element type
x:ClassModifier Root element, must beused with x:Class
The class visibility (public by default)
x:FieldModifier Element, must be usedwith x:Name
Visibility of the field created behindthe element
x:Key Element that its parentimplements IDictionary
Key in a dictionary
x:Name Element The element’s name, used for a fieldname for that element
© Alon Fliess
x:Type Element Give the type of the element e.g. fortests like TargetType = "{x:TypeButton}
43 von 171School of Engineering © K. Rege, ZHAW
Summary
■ XAML is used to define a Windows App user interface
■ It declaratively allows object creation, property and event assignment
■ A code-behind file will usually contain the logic
© Alon Fliess
44 von 171School of Engineering © K. Rege, ZHAW
Basic Concepts
45 von 171School of Engineering © K. Rege, ZHAW
Agenda
■ Logical and Visual Trees
■ Dependency Properties
■ Attached Properties
■ Routed Events
■ Attached Events
■ Resources
■ Summary
© Alon Fliess
46 von 171School of Engineering © K. Rege, ZHAW
Logical and Visual Trees
47 von 171School of Engineering © K. Rege, ZHAW
PagePage
StackPanelStackPanel
ButtonButton ListBoxListBox
ListBoxItemListBoxItem ListBoxItemListBoxItem
BorderBorder
TextBlockTextBlock
Logical Tree - Defined Structure
■ A tree of elements/controls making up the user interface;■ the essential structure of your UI.■ closely matches the elements you declare in XAML, and excludes most
visual elements created internally to help render the elements you declared.■ used to determine dependency property value inheritance,
resource resolution, etc.
<Page x:Class="UWPDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <Button
Content="OK" Background="Red" Margin="6"/> <ListBox Margin="6" > <ListBoxItem Margin="2"> <Border BorderThickness="4"> <TextBlock
Text="Hello" FontSize="20" /> </Border> </ListBoxItem> <ListBoxItem Content="Item 2" /> </ListBox> </StackPanel></Page>
© Alon Fliess
48 von 171School of Engineering © K. Rege, ZHAW
"Live" Visual Tree - Actual Tree
■ The actual visual objects that are making
up a logical tree■ Generated from the control template■ Can be inspected in
■ programmatically■ by a Tool in Debug Mode
■ Live Visual Tree Tool allows to observe
XAML visual tree in runtime
■ review properties of elements
■ change properties in runtime
■ without restarting application itself.
© Alon Fliesshttps://blogs.msdn.microsoft.com/cdndevs/2015/08/07/live-visual-tree-in-visual-studio-3/
49 von 171School of Engineering © K. Rege, ZHAW
Traversing the Trees at runtime
■ The logical and visual trees can be examined programmatically using the staticclasses System.Windows.LogicalTreeHelper andWindows.Media.VisualTreeHelper
■ VisualTreeHelper■ GetParent, GetChild, GetChildrenCount
■ LogicalTreeHelper■ GetParent, GetChildren, GetChildrenCount
© Alon Fliess
50 von 171School of Engineering © K. Rege, ZHAW
Properties
51 von 171School of Engineering © K. Rege, ZHAW
Properties
■ Properties are the values that are stored with the various XAML Elements
■ Each Element may have quite a lot of them
■ A XAML GUI may have hundreds of Elements■ Thousands of Properties■ For each Property (used or not) memory has to be provided
PropertiesPropertiesPropertiesPropertiesPropertiesPropertiesPropertiesProperties
52 von 171School of Engineering © K. Rege, ZHAW
Custom (CLR) Properties in a separate Class
■ For this, first a new Class Library with the class has to be created
■ Then a new Namespace is introduced (reference to Assembly in Project!)
namespace DataLib { public class Person { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() => $"{FirstName} {LastName}";
}}
<Window x:Class="WpfApp2.MainWindow" ... xmlns:datalib="clr-namespace:DataLib;assembly=DataLib" ... mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <StackPanel> <Label>Hello World</Label> <ListBox> <datalib:Person FirstName= "Stephany" LastName = "Nagel" /> <datalib:Person FirstName= "Matthias" LastName = "Nagel" /> </ListBox> </StackPanel></Window>
CLR PropertiesCLR Properties
53 von 171School of Engineering © K. Rege, ZHAW
Disadvantage of CLR Properties
■ The container for the Properties is an Object
■ Thus, for every Property the according memory space has to be provided,
independently of its usage
■ As mentioned, XAML defines thousands of properties■ thus a XAML GUI would waste a considerable amount memory
■ -> For XAML a special type of Properties has been introduced:■ Uses less Memory■ Support Change Notification Events
■ The Dependency Properties
54 von 171School of Engineering © K. Rege, ZHAW
Dependency Properties
55 von 171School of Engineering © K. Rege, ZHAW
Dependency Properties
■ Dependency properties are the "workhorse" of any XAML based technology
■ Dependency Property can used over a CLR property in the following scenarios■ If you want to set the style■ If you want data binding■ If you want to set with a resource (a static or a dynamic resource)■ If you want to support animation
■ Are be registered by calling the DependencyProperty.Register method
■ Almost all WPF properties are dependency Properties
© Alon Fliess
56 von 171School of Engineering © K. Rege, ZHAW
Advantages of Dependency Properties
■ Dependency Properties vs CLR Properties
■ CLR properties can directly read/write from the private member of a class by
using getter and setter. Thus, for every property used or not, the accordingmemory space has to be provided
■ In contrast, dependency properties are not stored in local objects■ saves memory because it stores the property only when accessed.
■ Dependency properties are stored in a dictionary of key/value pairs instead■ that is provided by the DependencyObject base class.
■ Dependency Properties may generate an Event that is fired when they are
changed (-> Data Binding)
© Alon Fliess
57 von 171School of Engineering © K. Rege, ZHAW
WPF Dependency Properties
■ Sample of some application of Dependency Properties in WPF■ since almost all properties in WPF are Dependency Properties anyway
■ Shows a button and when mouse hovers over it, text turns red
58 von 171School of Engineering © K. Rege, ZHAW
Custom Dependency Properties
■ The Names of the property are defined in the registration, e.g. "Value"
■ The Values itself are stored in a Collection handled by the base class■ The Values are always accessed by the Get/Set Method
■ via a reference to a static DependencyProperty variable■ the redundant CLR "Value" here is merely for convenience in the C# Code
■ With the registration also the type of the property, type of the owner, the initial
value are specified, and when an Event is fired. public class MyDependencyObject : DependencyObject { public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } }
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(int),
typeof(MyDependencyObject), // owner new PropertyMetadata(0, OnValueChanged)); } }
59 von 171School of Engineering © K. Rege, ZHAW
Attached Properties
■ Special kind of dependency properties
■ May be “attached” to objects of different types than the declaring type■ Declared with the static DependencyProperty.RegisterAttached method
■ Allows “context” properties■ E.g. Canvas.Left for elements that happen to be in a Canvas element
■ Can be set on any object
■ XAML■ An attribute with Type.Property syntax is used
■ In code■ The type exposes a SetXxx and a GetXxx with the element reference
© Alon Fliess
60 von 171School of Engineering © K. Rege, ZHAW
Attached Properties Example
■ XAML
■ Code
<Canvas> <Button x:Name="cmdOK" Canvas.Left="30" Canvas.Top="20" Content="OK" Padding="10" FontSize="26"> </Button></Canvas>
Canvas.SetLeft(cmdOK, 30);Canvas.SetTop(cmdOK, 20);
cmdOK.SetValue(Canvas.LeftProperty, 30);cmdOK.SetValue(Canvas.TopProperty, 30);
© Alon Fliess
61 von 171School of Engineering © K. Rege, ZHAW
Layout
62 von 171School of Engineering © K. Rege, ZHAW
Layout
■ Layout is the arranging of user interface elements within some container
■ Older technologies (e.g. Windows Forms) exact position and sizes may be
applied■ Limited in flexibility and adaptability■ However:
■ By use of Forms Anchors, etc also flexible layout is feasible■ With the Canvas also absolute positioning is possible
■ XAML provides several layout panels that can control dynamically size and
placement of elements
■ Elements may advertise their size and position needs
63 von 171School of Engineering © K. Rege, ZHAW
Size and Position of Elements
■ Element sizing and positioning is determined by■ the element itself■ its logical parent
■ A child element may request various settings
■ But the parent panel does not have to comply
64 von 171School of Engineering © K. Rege, ZHAW
Element Layout Properties
Panel
Margin
ContentContent
Padding
VerticalAlignment
Width
Height
LayoutTransformFlowDirection
Element/ControlHorizontalAlignment
■ XAML Elements define various Properties to give hints to their container for their
sizing and positioning (i.e. Layout)
65 von 171School of Engineering © K. Rege, ZHAW
Element Size
■ Width and Height properties (from Base Class FrameworkElement)
■ Control the exact size of the element
■ Default value is Double.NaN
■ Meaning: be as large as it needs to be
■ usually a bad idea to use these properties
■ Prevents smart resizing by panel
■ Reasonable only in a Canvas
■ Use MinWidth, MinHeight, MaxWidth, MaxHeight instead
■ Defaults are 0 for MinWidth, MinHeight
■ Double.PositiveInfinity for MaxWidth, MaxHeight
“Infinity” in XAML“Infinity” in XAML
66 von 171School of Engineering © K. Rege, ZHAW
More Size Related Properties
Read only properties
■ DesiredSize
■ Set indirectly by elements to report their desired size to their parent
■ Internally used by panels
■ RenderSize
■ The actual size the element is rendered with
■ ActualWidth, ActualHeight
■ Just the components of RenderSize (RenderSize.Width, RenderSize.Height)
67 von 171School of Engineering © K. Rege, ZHAW
Margin and Padding
■ Both of type Thickness (value type)■ Maintains the properties Left, Top, Right, Bottom indicating distance from the corresponding
edge
■ Margin
■ The amount of space to add around the element
■ Padding
■ The amount of space to add around the content of the control
68 von 171School of Engineering © K. Rege, ZHAW
Visibility
■ Visibility of elements is determined by the Visibility property (from
UIElement) of the Windows.Visibility enumeration■ Visible
■ The element is rendered and participates in layout■ Collapsed
■ The element is invisible and does not participate in layout
69 von 171School of Engineering © K. Rege, ZHAW
Element Positioning
■ Finally, element position is determined by the containing panel policy■ Simple X,Y is possible but is not the usual case
■ Elements can indicate their position constraints or preferences to their containingpanel
70 von 171School of Engineering © K. Rege, ZHAW
Layout Panels
71 von 171School of Engineering © K. Rege, ZHAW
Layout Panels
■ Layout panels derive from the abstract Windows.Controls.Panel class
■ Each child element can be a panel as well■ Allows creation of complex and adaptive user interfaces
■ WPF provides several built in panels with specific Layout policies
■ Custom layout panels can be created as well
72 von 171School of Engineering © K. Rege, ZHAW
WPF Layout Panels
■ Main layout panels are
■ Canvas
■ Arranges children in a 2D coordinate system
■ StackPanel
■ Arranges children in a horizontal or vertical “stack”
■ DockPanel
■ Arranges children horizontally or vertically to each other towards the edges
■ WrapPanel
■ Arranges children continuously horizontally or vertically, flowing to the next row/column
■ Grid
■ Arranges children in a flexible grid
73 von 171School of Engineering © K. Rege, ZHAW
Canvas
■ Canvas is the most simple layout
■ All the controls are positioned absolutely
■ Cartesian xy-Coordinate are applied
■ Canvas provides the embedded components with attributes Canvas.RightCanvas.Left, Canvas.Top Canvas.Bottom
■ Height and Width are set by the embedded control elements
© Dr. Beatrice Amrhein
74 von 171School of Engineering © K. Rege, ZHAW
Canvas Example 1
© Dr. Beatrice Amrhein
75 von 171School of Engineering © K. Rege, ZHAW
Canvas Example 2
76 von 171School of Engineering © K. Rege, ZHAW
The StackPanel
■ Stacks its elements in a vertical or horizontal “stack”
■ Orientation property■ Vertical (default) or Horizontal
■ Alignment is ignored in the direction of stacking
77 von 171School of Engineering © K. Rege, ZHAW
Alignment
■ Alignment indicates what should be done with any extra space given to an
element
■ HorizontalAlignment■ Left, Right, Center, Stretch
■ VerticalAlignment■ Top, Bottom, Center, Stretch
<StackPanel TextBlock.FontSize="20" Margin="4">
<Button HorizontalAlignment="Left" Background="Red">Left</Button>
<Button HorizontalAlignment="Center" Background="Orange">Center</Button>
<Button HorizontalAlignment="Right" Background="Yellow">Right</Button>
<Button HorizontalAlignment="Stretch" Background="Lime">Stretch</Button>
</StackPanel>
78 von 171School of Engineering © K. Rege, ZHAW
Content Alignment
■ Similar to element alignment
■ What to do with extra space when the content is smaller than its control
■ HorizontalContentAlignment
■ VerticalContentAlignment
<StackPanel TextBlock.FontSize="20" Margin="4">
<Button HorizontalContentAlignment="Left" Background="Red">Left</Button>
<Button HorizontalContentAlignment="Center" Background="Orange">Center</Button>
<Button HorizontalContentAlignment="Right" Background="Yellow">Right</Button>
<Button HorizontalContentAlignment="Stretch" Background="Lime">Stretch</Button>
</StackPanel>
Westboro Baptist Church Kan.Westboro Baptist Church Kan.
79 von 171School of Engineering © K. Rege, ZHAW
Flow Direction
■ The FlowDirection property indicates the flow of layout■ LeftToRight (the default)■ RightToLeft
■ The RightToLeft setting reverses the meaning of “left” and “right”
80 von 171School of Engineering © K. Rege, ZHAW
The Grid
■ The most versatile and useful panel
■ Usually used as the top-level panel■ Visual Studio and Expression Blend windows/user controls start this way
■ Arranges its children in a multi-row and multi-column way■ Their sizes and number can be manipulated in interesting ways■ Somewhat similar to an HTML table
81 von 171School of Engineering © K. Rege, ZHAW
Creating a Grid
■ For rows■ Set the RowDefinitions property■ Add a RowDefinition object for each row
■ Set any special properties
■ For columns■ Set the ColumnDefinitions property■ Add a ColumnDefinition object for each column
■ Set any special properties
■ For each element■ Set the Grid.Row and Grid.Column attached properties (default is 0, 0)
82 von 171School of Engineering © K. Rege, ZHAW
Sizing Rows and Columns
■ By default, all rows are of equal height and all columns are of equal width■ Can change the height of a row using the RowDefinition.Height property
■ Can change the width of a column using the ColumnDefinition.Width property■ Each one of type GridLength■ The unit is controlled by the GridUnitType property
■ Auto – size as required by content
■ Pixel – size is the number specified■ Star – size is a weighted proportional (default)
■ “*”, “2*”, etc. in XAML■ Spanning
■ A row may span more than one column and vice versa■ Can be set by the Grid.RowSpan and Grid.ColumnSpan attached properties
■ Default for both is 1
83 von 171School of Engineering © K. Rege, ZHAW
Example:
■ Example of Form with GridPanel
<Grid x:Name = "FormLayoutGrid" Background = "LightGray">
<Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions>
<Grid.RowDefinitions> <RowDefinition Height = "*" /> <RowDefinition Height = "*" /> <RowDefinition Height = "*" /> </Grid.RowDefinitions>
<TextBlock Grid.Row = "0" Grid.Column = "0" Text = "Name" Margin = "10" HorizontalAlignment = "Left" VerticalAlignment = "Center" Width = "100"/>
<TextBox Grid.Row = "0" Grid.Column = "1" Margin = "10"/> <TextBlock Grid.Row="1" Grid.Column="0" Text="ID" Margin="10"
HorizontalAlignment = "Left" VerticalAlignment = "Center" Width = "100"/>
<TextBox Grid.Row = "1" Grid.Column = "1" Margin = "10"/> <TextBlock Grid.Row = "2" Grid.Column = "0" Text = "Age"
Margin = "10" HorizontalAlignment = "Left" VerticalAlignment="Center" Width = "100"/>
<TextBox Grid.Row = "2" Grid.Column = "1" Margin = "10"/>
</Grid>
as height asthe control
as height asthe control
stretchesremaining space
stretchesremaining space
84 von 171School of Engineering © K. Rege, ZHAW
Controls
85 von 171School of Engineering © K. Rege, ZHAW
What is a Control?
■ Controls are elements capable of receiving focus and handling input■ Behavior is the distinction, not looks
■ Many controls are available “out of the box”
■ Also new, individual controls can be created■ User controls that wrap one or more controls and expose higher level properties■ Custom controls that derive from an existing control and extend its functionality
86 von 171School of Engineering © K. Rege, ZHAW
Simple Example: Static Text
■ The TextBlock (Control-)Element■ The Text property■ Font related properties
■ FontSize, FontFamily, etc.■ TextAlignment, TextTrimming, TextDecorations
■ An optional collection of “inlines”■ Replacement for the Text property■ Inheriting from the abstract Inline class
■ Hyperlink, Bold, Run, Span, Underline, Italic, LineBreak
87 von 171School of Engineering © K. Rege, ZHAW
Example: TextBlock
<TextBlock FontSize="16" Margin="4"> <Run Text="Hello" /> <Bold> Hello <Italic>Hello</Italic> </Bold> <LineBreak /> <Hyperlink>Go to my web site</Hyperlink> <LineBreak /><LineBreak /> <Underline>This line is underlined</Underline> <LineBreak /> <Span FontSize="20"> Hello in Bigger Font </Span></TextBlock>
■ A structured Text à la HTML cdn be composed within a TextBlock
88 von 171School of Engineering © K. Rege, ZHAW
Other Controls
https://msdn.microsoft.com/en-us/library/windows/apps/mt185406.aspx
89 von 171School of Engineering © K. Rege, ZHAW
Styles
90 von 171School of Engineering © K. Rege, ZHAW
Styles
■ Styles are used to specify the appearance of the Elements itselfs
■ Usually defined as a resource
■ Can be applied to any element with the Style property
■ Any specific property changed by the element that conflicts with the style takesprecedence over the style setting
91 von 171School of Engineering © K. Rege, ZHAW
Style Example
<Page x:Class="Demo.StyleWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Style Demo" SizeToContent="WidthAndHeight">
<Window.Resources>
<Style x:Key="fancyButton">
<Setter Property="Button.Background" Value="Purple" />
<Setter Property="Button.FontSize" Value="20" />
<Setter Property="Button.FontWeight" Value="Bold" />
<Setter Property="Button.Foreground" Value="Yellow" />
<Setter Property="Button.Margin" Value="4" />
<Setter Property="Button.LayoutTransform">
<Setter.Value>
<RotateTransform Angle="15" />
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel Margin="4">
<Button Content="Click Me" Style="{StaticResource fancyButton}" />
<Button Content="Hello" Style="{StaticResource fancyButton}" />
<Button Content="Me Fancy" Style="{StaticResource fancyButton}" />
</StackPanel>
</Page>
92 von 171School of Engineering © K. Rege, ZHAW
Restricting Style Usage
■ A style may be restricted to work on certain types using the TargetType
property■ And on any derived types
■ In this case, the full property qualification is unnecessary
<Style x:Key="fancyButton" TargetType="{x:Type Button}"> <Setter Property="Background" Value="Purple" /> <Setter Property="FontSize" Value="20" /> <Setter Property="FontWeight" Value="Bold" /> <Setter Property="Foreground" Value="Yellow" /> <Setter Property="Margin" Value="4" /> <Setter Property="LayoutTransform"> <Setter.Value> <RotateTransform Angle="15" /> </Setter.Value> </Setter></Style>
93 von 171School of Engineering © K. Rege, ZHAW
Implicit Styles
■ With the TargetType property the x:Key attribute may be omitted
■ The style will automatically apply to all elements of the specified type■ The exact type only (not a derived type)
■ Elements can still override properties or use a different style, or clear the style bysetting it to null
94 von 171School of Engineering © K. Rege, ZHAW
Data Binding
95 von 171School of Engineering © K. Rege, ZHAW
What is Data Binding?
■ Data in WPF can reference any .NET object
■ Data binding means tying two arbitrary objects
■ Typical scenario is a non-visual object (or collection) to a visual element
■ Any changes to the non-visual object are reflected in the visual element (and
optionally vice versa)
96 von 171School of Engineering © K. Rege, ZHAW
Data Binding Concepts
■ Source■ The data object to bind to
■ Property Path■ The property on the source object to use■ May be a nested property, an array element or an indexer
■ Target■ The target object to modify■ Must be a dependency property
■ Binding Mode■ Typically one way or two way (target update source)
97 von 171School of Engineering © K. Rege, ZHAW
Using Data Binding
■ Typically done in XAML using the {Binding} markup extension■ The Binding class is the workhorse behind the scenes■ Set on the target property
■ Can be done programmatically in code■ Common scenario is when building custom Control
■ Supported by Visual Studio
98 von 171School of Engineering © K. Rege, ZHAW
Example 1: Element Binding Label to TextBox
■ The content of the label should be
dependent of the content of a Textbox
■ In the property window chose the label
and specify the content
■ Click the black rectangle and a pop upwindow appears
© Dr. Beatrice Amrhein
99 von 171School of Engineering © K. Rege, ZHAW
… Element Binding Label
■ Choose the line «create data binding»
the window below appears. We choose
for binding type the "ElementName"
■ With «ElementName» anther selection
appears and the Textbox is chosen
© Dr. Beatrice Amrhein
100 von 171School of Engineering © K. Rege, ZHAW
… Element Binding Label
■ For «Path» we choose the entry «Text:
(String)» and press ok.
■ The XAML code is generated
accordingly
© Dr. Beatrice Amrhein
101 von 171School of Engineering © K. Rege, ZHAW
Result
■ After the start of the application the entered content of the TextBox and the label
are synchronized.
© Dr. Beatrice Amrhein
102 von 171School of Engineering © K. Rege, ZHAW
Example 2: Bind Label to a ListBox entry
■ The selected item in the ListBox should be shown in the label
© Dr. Beatrice Amrhein
103 von 171School of Engineering © K. Rege, ZHAW
… Bind Label to ListBox entry
■ Proceed as before but choose ListBox this time
© Dr. Beatrice Amrhein
104 von 171School of Engineering © K. Rege, ZHAW
Generated Code of the Property Editor
© Dr. Beatrice Amrhein
The generated code is not yet completeand has to be fixed in the XAML file
105 von 171School of Engineering © K. Rege, ZHAW
Add "Content" to Fix Code
© Dr. Beatrice Amrhein
106 von 171School of Engineering © K. Rege, ZHAW
Or Use C# Code instead
■ Alternatively the data binding can also be specified programmatically
© Dr. Beatrice Amrhein
107 von 171School of Engineering © K. Rege, ZHAW
The Binding Class
108 von 171School of Engineering © K. Rege, ZHAW
The Binding Class
■ Is used to connect■ a Data Target (usually a WPF-Element) and■ a Data Source (e.g. an arbitrary Data Object, a DataBase, an XML Data Structure)
© Dr. Beatrice Amrhein
109 von 171School of Engineering © K. Rege, ZHAW
… The Binding Class
■ A Binding comprises a binding targed (with additional constraints) a bindingsource with additionally the path to the value of the source. This binding can be
specified by XAML or by C# code.
■ In XAML a binding is created by <Binding ….> e.g.
<Binding ElementName=" . . . " Path=" . . . "/>
■ In C# the binding object is a instatiation of the binding class
Binding b = new Binding(. . .).© Dr. Beatrice Amrhein
110 von 171School of Engineering © K. Rege, ZHAW
Example 1: Data Binding to a C# Person Object
■ The state of a Model should automatically be synchronized with the View
© Dr. Beatrice Amrhein
111 von 171School of Engineering © K. Rege, ZHAW
The Data Source: The Class Person
© Dr. Beatrice Amrhein
112 von 171School of Engineering © K. Rege, ZHAW
Instantiate Object and define Data Source
© Dr. Beatrice Amrhein
113 von 171School of Engineering © K. Rege, ZHAW
Specify Binding in the XAML Code
© Dr. Beatrice Amrhein
114 von 171School of Engineering © K. Rege, ZHAW
Result
■ The state (values) of the Model is synchronized with the view
■ Any Change in the TextBoxes is passed to the Model
© Dr. Beatrice Amrhein
115 von 171School of Engineering © K. Rege, ZHAW
Example 2: The Class Inscription
© Dr. Beatrice Amrhein
116 von 171School of Engineering © K. Rege, ZHAW
… The Class Inscription
© Dr. Beatrice Amrhein
117 von 171School of Engineering © K. Rege, ZHAW
Binding in the XAML Code
© Dr. Beatrice Amrhein
118 von 171School of Engineering © K. Rege, ZHAW
The Different Syntaxes of the Binding Element
■ Given a DataContext MyRecord
■ The three binding syntaxes (below) function identically:
https://blogs.msdn.microsoft.com/jerrynixon/2012/10/12/xaml-binding-basics-101/
119 von 171School of Engineering © K. Rege, ZHAW
The Binding Properties
Property Meaning
ElementName Specifies the name of the data source
Path Path ist the Property to which the data are bound: (Content,Value, Text, …)
Mode Define Binding Direction, e.g. One Way etc.
Converter Defines the object that is used for conversion
Source Reference to the source object
UpdateSourceTrigger
Defines when data should be actualized (e.g. every time somedata value has changed)
120 von 171School of Engineering © K. Rege, ZHAW
Binding Mode i.e. Direction
■ The Mode attribute allows specifying how the target / source properties are
updated
■ Mode property (of type enum BindingMode)
Binding Mode Meaning
OneWay The target property is updated by source property changes
TwoWay OneWay + the source property is updated by changes of thetarget property
OneWayToSource Similar to OneWay, but from target to sourceFor source properties that are not dependency properties
OneTime Target is updated by the source the first time they are bound
Default Depends on the target property.TwoWay for user settable properties, OneWay for everythingelse.This is the default value
121 von 171School of Engineering © K. Rege, ZHAW
Update Trigger Modes
■ Updates from the source property to the target property happen immediately
■ In a TwoWay or OneWayToSource bindings, the source is updated by the target
based on the UpdateSourceTrigger property
UpdateSourceTrigger Meaning
PropertyChanged The source is updated whenever the target changes
LostFocus The source is updated when the target property’s element loses focus
Explicit The source is updated only when the methodBindingExpression.UpdateSource is called
Default Depends on the target property(FrameworkPropertyMetadata.DefaultUpdateSourceTrigger property)
122 von 171School of Engineering © K. Rege, ZHAW
Binding to Objects
■ The Object that content is used can be specified
■ Explicitly via Source Property in Binding■ Reference to the source name in the Binding
■ Implicitly by the DataContext■ Used by default if Source or RelativeSource is not specified
■ RelativeSource (not covered here)■ Sets the source based on the “location” of the target in the layout tree■ Useful in data and control templates
123 von 171School of Engineering © K. Rege, ZHAW
Model Change Notifications
■ If data source object properties are changed from e.g. another view
■ An object that act as a data source must notify the view(s) when one of its
properties changes
■ Simple: By defining the property as a dependency property■ The notification mechanism is built in
■ Or by implementing the INotifyPropertyChanged interface■ Raise the PropertyChanged event
■ Will be covered later together with the event handling
124 von 171School of Engineering © K. Rege, ZHAW
EventProcessing
125 von 171School of Engineering © K. Rege, ZHAW
Introduction
■ An Event is fired when the state of the GUI or underlying data (or application)
has changed. Events may indicate:■ A button has been clicked■ The Text of a Textbox has changed■ The Size of a Window or Control has changed■ The Mouse Pointer has moved■ ….
■ For every Event the registered Event Listeners are notified
© Dr. Beatrice Amrhein
126 von 171School of Engineering © K. Rege, ZHAW
Some Important Events
■ Press of a mouse button results in a Click-Event.
■ A focusable component (Button, Text-Component, Window, …) has been clickedi.e. activated (GotFocus).
■ Another component has been clicked; the formed component lost is focus
(LostFocus)
■ The content of a TextBox has changed (TextChanged)
■ ...
© Dr. Beatrice Amrhein
127 von 171School of Engineering © K. Rege, ZHAW
Example 1: Attach a Click-Event to a Button
© Dr. Beatrice Amrhein
128 von 171School of Engineering © K. Rege, ZHAW
… Attach a Click-Event to a Button
© Dr. Beatrice Amrhein
129 von 171School of Engineering © K. Rege, ZHAW
… Attach a Click-Event to a Button
© Dr. Beatrice Amrhein
130 von 171School of Engineering © K. Rege, ZHAW
… Attach a Click-Event to a Button
© Dr. Beatrice Amrhein
131 von 171School of Engineering © K. Rege, ZHAW
… Attach a Click-Event to a Button
© Dr. Beatrice Amrhein
132 von 171School of Engineering © K. Rege, ZHAW
… Attach a Click-Event to a Button
© Dr. Beatrice Amrhein
133 von 171School of Engineering © K. Rege, ZHAW
Example 2: Mouse-Event: MainWindow.xaml
© Dr. Beatrice Amrhein
134 von 171School of Engineering © K. Rege, ZHAW
… Mouse-Event: MainWindow.xaml.cs
© Dr. Beatrice Amrhein
135 von 171School of Engineering © K. Rege, ZHAW
Example 3: Property Changed Event
© Dr. Beatrice Amrhein
136 von 171School of Engineering © K. Rege, ZHAW
… Property Changed Event
© Dr. Beatrice Amrhein
137 von 171School of Engineering © K. Rege, ZHAW
… Property Changed Event: Code Behind
© Dr. Beatrice Amrhein
138 von 171School of Engineering © K. Rege, ZHAW
… Property Changed Event: Data
© Dr. Beatrice Amrhein
139 von 171School of Engineering © K. Rege, ZHAW
… Property Changed Event: Fire Event
© Dr. Beatrice Amrhein
140 von 171School of Engineering © K. Rege, ZHAW
… Property Changed Event
© Dr. Beatrice Amrhein
141 von 171School of Engineering © K. Rege, ZHAW
The Events Fired
© Dr. Beatrice Amrhein
142 von 171School of Engineering © K. Rege, ZHAW
MVVM and Commands
143 von 171School of Engineering © K. Rege, ZHAW
The MVVM Pattern
■ Model – View – ViewModel
■ Based on similar principles of Model View Controller (MVC) and ModelView Presenter (MVP)
■ Natural pattern for XAML based applications■ Data binding is key
■ Enables developer-designer workflow
■ Increases application portability
ModelModel
ViewView ViewModelViewModel
Commands,Properties,Behaviors
Methods,Properties
ModelModelModelModel
Events
While MVC's Control is Modelindependent the ViewModel ismodel specific
While MVC's Control is Modelindependent the ViewModel ismodel specific
144 von 171School of Engineering © K. Rege, ZHAW
MVVM Participants
■ Model - the data container (also persistent data e.g. data base)■ Business logic and data
■ May implement change notification for properties and collections
■ View - the data presenter■ Data display and user interactivity
■ Implemented as a Page or Window or custom control
■ Has little or no code behind
■ ViewModel - the data processor■ UI logic and data for the View
■ Abstracts the Model for View usage
■ Exposes commands (ICommand) to be used by the View
■ Implements change notifications
■ Maintains state for the View (communicates via data binding)
While MVC's Control is Modelindependent the ViewModel isheavily model specific
While MVC's Control is Modelindependent the ViewModel isheavily model specific
145 von 171School of Engineering © K. Rege, ZHAW
The View (written mainly in XAML)
■ Provides the user interface and interaction
■ The DataContext property points to the View Model
■ Updated using property changes from the ViewModel
■ Binds to commands (on ICommandSource elements) provided by the
ViewModel
146 von 171School of Engineering © K. Rege, ZHAW
The ViewModel (written in C#)
■ Exposes properties the View binds to
■ Most of the functionality is implemented here
■ Can be an adapter if some functionality missing from Model classes
■ Exposes commands to be invoked by the view
■ Maintains state for the View
■ Notifies View of changes■ Uses Dependency Properties■ Implements change notifications (INotifyPropertyChanged)■ Uses e.g. ObservableCollection<T> that already implements INotifyCollectionChanged
147 von 171School of Engineering © K. Rege, ZHAW
Wiring the View and the View Model
■ The View’s DataContext must be set to its supporting ViewModel
■ Some options■ The View can create an instance of the right VM (even in XAML)■ The ViewModel can be injected using some dependency injection technique (e.g. Unity or MEF)■ Use some global ViewModel locator object■ A Main VM can be set explicitly on the main View, and other VMs can be exposed as properties,
which will be bound by child views
148 von 171School of Engineering © K. Rege, ZHAW
The Model (written in C#)
■ Responsible for data access (storage), e.g.■ Data Transfer Objects (DTO)■ POCOs (Plain Old CLR Objects)■ Generated entity objects■ Generated proxy objects
■ May provide change notifications
■ Provides validation if appropriate
149 von 171School of Engineering © K. Rege, ZHAW
Commands
150 von 171School of Engineering © K. Rege, ZHAW
Introduction to Commands
■ Handling events and executing some code is fine for simple applications
■ Sometimes the same code needs to execute from unrelated events (e.g. mouse
click, keyboard shortcut, menu item, toolbar)
■ Maintaining UI state (e.g. enabled/disabled) becomes difficult
■ Higher level functionality, such as an undo / redo system is not possible
■ Solution: use commands (the “Command” design pattern) with some support
from WPF
151 von 171School of Engineering © K. Rege, ZHAW
The Command
■ A command is an object implementing theSystem.Windows.Input.ICommand interface
public interface ICommand { event EventHandler CanExecuteChanged; bool CanExecute(object parameter); void Execute(object parameter);}
152 von 171School of Engineering © K. Rege, ZHAW
Commands for MVVM
■ MVVM frameworks typically provide a basic ICommand implementation that uses
a delegate■ Class typically call DelegateCommand
■ Using commands in MVVM
■ Some controls expose a Command and CommandParameter properties that can
be bound to a command exposed by the ViewModel■ e.g. ButtonBase, Hyperlink and MenuItem expose these
153 von 171School of Engineering © K. Rege, ZHAW
Some Command are Predefined
■ For TextBoxes are the some Command already implemented
154 von 171School of Engineering © K. Rege, ZHAW
Use of Predefined Commands
■ To Use these Commands only the according Name has to be specified
155 von 171School of Engineering © K. Rege, ZHAW
Write Custom Commands
■ Write the according Commands in the Code Behind File
156 von 171School of Engineering © K. Rege, ZHAW
… Write Custom Commands
■ In the XAML File define the according Command Binding
157 von 171School of Engineering © K. Rege, ZHAW
Summary
■ Commands allow high level segregation of tasks
■ The MVVM pattern is common in WPF to separate logic from UI and increase
testability
158 von 171School of Engineering © K. Rege, ZHAW
Asynchronous Event Processingin WPF
159 von 171School of Engineering © K. Rege, ZHAW
Asynchronous Operations
■ WPF, like other UI technologies, is single threaded (STA)
■ but long operations may freeze the UI
■ < 10 Seconds -> change cursor
■ >10 Seconds, < 5h: provide a Dialog with a progress indicator (also offer cancel option)
■ > 5h Play Video "Lord of the Ring "
■ Use Async Event Handler
https://stackoverflow.com/questions/1568557/how-can-i-make-the-cursor-turn-to-the-wait-cursor
view.OnRefreshClicked += new EventHandler(async (s, e) => await RefreshObjectExplorerAsync());
160 von 171School of Engineering © K. Rege, ZHAW
Using the Dispatcher (see last lecture)
■ Asynchronous operations on the UI thread can be scheduled using the
Dispatcher object responsible for that UI thread
■ Accessible using Dispatcher.CurrentDispatcher static property if on the UI thread
■ Or by calling DispatcherObject.Dispatcher instance property (which is inherited by all WPF
elements)
■ Or use AsyncHelper extension methods (see last lecture)
■ An operation can be scheduled using the Invoke or BeginInvoke methods■ Accept at least a delegate and an optional DispatcherPriority■ .NET 4.5 also adds InvokeAsync variants
■ DispatcherPriority enumeration■ Indicates the priority to process the operation■ Lower priorities can assume higher priority operations have already completed■ Default is DispatcherPriority.Normal
161 von 171School of Engineering © K. Rege, ZHAW
Updating the UI (see last lecture)
■ When doing work on a background thread (either explicitly created or using the
thread pool or task), some result may need to update WPF elements■ Accessing the object directly will cause an exception
■ Need to marshal the required operation to the UI thread using the Dispatcher■ Call Invoke (for synchronous invocation) or BeginInvoke/InvokeAsync (for asynchronous
invocation)■ Specify a priority for the update operation (usually DispatcherPriority.Normal)
162 von 171School of Engineering © K. Rege, ZHAW
Questions?
Uff!Yeep!
163 von 171School of Engineering © K. Rege, ZHAW
Binary Ressources
164 von 171School of Engineering © K. Rege, ZHAW
Binary Resources
■ The resources that can be used by any .NET application■ Usually store bitmaps, icons, etc.
■ Packaging■ Embedded inside an Assembly■ Loose files that are known to the application at compile time■ Loose files that are not known to the application at compile time
■ May be localized
165 von 171School of Engineering © K. Rege, ZHAW
Defining Binary Resources
■ Binary resources can be embedded using Visual Studio by adding theresource and selecting an action type
■ Resource■ Embedded inside the assembly
■ Content■ Remains as a loose file, but an AssemblyAssociatedContentFile attribute is
added with the relative path of the file
■ Don’t use the Embedded Resource■ WPF can’t use such resources
166 von 171School of Engineering © K. Rege, ZHAW
Accessing Binary Resources
■ Binary resources that are added to the project as Content or Resourcecan be referenced easily, even if loose files are involved (as long as they
are in the folder of the executable or a subfolder)
<Button VerticalAlignment="Center" HorizontalAlignment="Center" > <StackPanel Orientation="Horizontal" > <Image Source="apple.png" Width="48" Height="48" Margin="4"/> <TextBlock Text="This is an Apple" FontSize="24"
VerticalAlignment="Center" Margin="4"/> </StackPanel></Button>
167 von 171School of Engineering © K. Rege, ZHAW
Data Templates
■ A data template is a piece of UI that describes how to display a source object
■ Various elements have properties of type DataTemplate just for this■ ContentControl has a ContentTemplate property■ ItemsControl has a ItemTemplate property■ HeaderedContentControl and HeaderedItemsControl have a HeaderTemplate property
■ With data binding, the source object is automatically set to the current object that
is being rendered
public interface IValueConverter {
object Convert(object value, Type targetType, object parameter, CultureInfo culture);
object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture);
}
168 von 171School of Engineering © K. Rege, ZHAW
Value Converters
■ A value converter can completely alter the way the source is interpreted into the
target
■ Often used to match source and target that are of incompatible types■ E.g. show a red background when the price of a book is greater than 50
■ A value converter implements the IValueConverter interface
■ Create an instance of the converter as a resource and use in a bindingexpression
public interface IValueConverter {
object Convert(object value, Type targetType, object parameter, CultureInfo culture);
object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture);
}
169 von 171School of Engineering © K. Rege, ZHAW
Converter Parameters
■ The “parameter” object is null by default■ Can be set using the ConverterParameter property of the Binding object
■ Not “bindable” in itself!
■ The culture info supplied is by default set to “en-US”■ A type converter exists that can be used via the ConverterCulture property of the Binding object
(e.g. “fr-CA”, “he-IL”)
■ The return value can be Binding.DoNothing, which cancels the binding
operation
170 von 171School of Engineering © K. Rege, ZHAW
Data Template Selectors
■ A way to replace a data template completely■ Cannot be done in XAML alone
■ Derive a class from DataTemplateSelector
■ Override the SelectTemplate method
■ Set the ItemTemplateSelector property on the ItemsControl element to
an instance of the custom template selector
171 von 171School of Engineering © K. Rege, ZHAW
Data Template Selector Example
<Window.Resources>
<local:AlternateTemplateSelector x:Key="tmpselect" EvenTemplate="tmp1" OddTemplate="tmp2" />
<DataTemplate x:Key="tmp1">
<TextBlock Margin="2" Background="Red" Foreground="White" FontSize="20" Text="{Binding}"/>
</DataTemplate>
<DataTemplate x:Key="tmp2">
<TextBlock Margin="2" Background="Yellow" Foreground="DarkBlue" FontSize="15" Text="{Binding}"/>
</DataTemplate>
</Window.Resources>
<ListBox Name="list" ItemTemplateSelector="{StaticResource tmpselect}"
HorizontalContentAlignment="Stretch"/>
public class AlternateTemplateSelector : DataTemplateSelector { public string OddTemplate { get; set; } public string EvenTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { return (DataTemplate)((FrameworkElement)container).FindResource(
(int)item % 2 == 0 ? EvenTemplate : OddTemplate); }}
var data = new List<int>();Random r = new Random();for(int i = 1; i < 100; i++) data.Add(r.Next(1, 100));list.ItemsSource = data;