Chapter 02 of the lecture Tool Development taught at SAE Institute Hamburg.
Introduction to WPF layout controls, error handling, menus and bars, commands and shortcuts.
3. Objectives
• To understand the different layouting mechanisms
of WPF
• To learn how to set up robust and consistent error
handling
• To get an overview of advanced WPF controls such
as menus and progress bars
3 / 58
4. WPF UI Layout
• Defined by location and size of all controls
• Has to adapt to changes in window size
• This is achieved by relative positioning.
• Determining the final layout is done in two steps:
1. Control tells its parent what location and size it
requires.
2. Parent tells the control what space it can have.
4 / 58
5. Canvas Control
Only panel element that has no inherent layout
characteristics. The ZIndex property determines the
order in which child elements that share the same
coordinate space appear.
Rendered View
5 / 58
6. Canvas Control
Only panel element that has no inherent layout
characteristics. The ZIndex property determines the
order in which child elements that share the same
coordinate space appear.
XAML
<Canvas Height="400" Width="400">
<Canvas Height="100" Width="100" Top="0" Left="0" Background="Red"/>
<Canvas Height="100" Width="100" Top="100" Left="100" Background="Green"/>
<Canvas Height="100" Width="100" Top="50" Left="50" Background="Blue"/>
</Canvas>
6 / 58
7. DockPanel Control
The position of child elements of a DockPanel on the
screen is determined by the Dock property of the
respective child elements and the relative order of
those child elements.
Rendered View
7 / 58
12. ScrollViewer Control
Enables content to be displayed in a smaller area
than its actual size. When the content of the is not
entirely visible, the ScrollViewer displays scrollbars.
Rendered View
12 / 58
13. ScrollViewer Control
XAML
13 / 58
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBlock>
Scrolling is enabled when it is necessary. Resize the window, making it larger and
smaller.
</TextBlock>
</StackPanel>
</ScrollViewer>
16. WrapPanel Control
Positions child elements in sequential position from
left to right, breaking content to the next line at the
edge of the containing box.
Rendered View
16 / 58
18. Star Sizing
• Distributes remaining space proportionally
• Controls receives a weighted proportion of the
remaining available space
• In contrast to Auto, which distributes space evenly
based on the size of the content
• Expressed as * or 2* in XAML
18 / 58
19. Error Handling
• Should be done by the Controller.
• Should provide rich and meaningful error
messages.
• Cause of the error
• What needs to be done to avoid the error
19 / 58
This must never happen. Never, never, never, never, never!
20. Excursus: C# Exceptions
• Help you deal with any unexpected or exceptional
situations that occur when a program is running
• Exceptions are types that all ultimately derive from
System.Exception.
• Exception objects contain detailed information
about the error, such as the state of the call stack
and a text description of the error.
• Generated by the common language runtime (CLR),
by the .NET Framework or any third-party libraries,
or by application code.
20 / 58
21. Throwing Exceptions
Exceptions are created by using the throw keyword.
if (width <= 0)
{
throw new ArgumentOutOfRangeException("width", "Width must be positive.");
}
21 / 58
C#
22. Handling Exceptions
Handling uses the try, catch, and finally keywords to
• try actions that may not succeed
• handle failures when you decide that it is reasonable to do so, and
• clean up resources afterward
try
{
this.map = new Map(width, height);
}
catch (ArgumentOutOfRangeException e)
{
MessageBox.Show(e.Message);
}
22 / 58
C#
23. Handling Exceptions
• Use a try block around the statements that might
throw exceptions.
• Once an exception occurs in the try block, the flow
of control jumps to the first associated exception
handler that is present anywhere in the call stack.
• If no exception handler for a given exception is
present, the program stops executing with an error
message.
23 / 58
25. Exception Best Practice
• Do not catch an exception unless you can handle it
and leave the application in a known state.
• Do not catch non-specific exceptions, such as
System.Exception.
• Use a finally block to release resources, for example
to close any streams or files that were opened in
the try block.
25 / 58
27. Common Exceptions
• Thrown by your application or the framework
• InvalidOperationException
• ArgumentException
• ArgumentNullException
• ArgumentOutOfRangeException
• Thrown by the CLR
• NullReferenceException
• IndexOfOutRangeException
• StackOverflowException
• OutOfMemoryException
27 / 58
28. Error Handling
• Encapsulate showing error messages in a dedicated
Controller method.
• Allows you to change the error handling at a single point
in your code later.
private void ShowErrorMessage(string title, string message)
{
MessageBox.Show(
message, title, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.Cancel);
}
28 / 58
C#
29. MessageBox in WPF
• Prefabricated modal dialog box that displays a text
message to a user
• Show a message box by calling the static Show
method of the MessageBox class
29 / 58
32. Commands in WPF
• Provide input handling at a more semantic level
than device input
• Separate the semantics and the object that invokes
a command from the logic that executes the
command
• Allows for multiple and disparate sources to invoke the
same command logic
• Allows the command logic to be customized for different
targets
• Indicate whether an action is available
32 / 58
33. WPF Command Example
• Cut selected objects or text
• By clicking a button
• By choosing an item in a menu
• By using a key combination, such as CTRL+X
• Only makes sense when something is selected
• Disable buttons and menu items so that the user knows
whether it is possible to perform an action
33 / 58
34. WPF Command Breakdown
• Command: Action to be executed
• Command source: Object which invokes the
command
• Command target: Object that the command is
being executed on
• Command binding: Object which maps the
command logic to the command
34 / 58
35. WPF Command Example
• Command: Paste
• Command source: MenuItem
• Command target: Textbox
• Command binding: Supplied by Textbox control
35 / 58
36. Custom Commands
• Created by implementing the ICommand interface:
• Method Execute: Performs the actions that are
associated with the command.
• Method CanExecute: Determines whether the command
can execute on the current command target.
• Event CanExecuteChanged: Raised if the command
manager that centralizes the commanding operations
detects a change in the command source.
• WPF implementation of ICommand is the
RoutedCommand class
36 / 58
38. Command Sources
• Implementations of ICommandSource
• e.g. MenuItem, Button
<MenuItem Command="ApplicationCommands.New"/>
38 / 58
XAML
39. Command Sources
• Input Bindings
• many predefined commands include a set of default input bindings
• keyboard binding "CTRL+C“
• Tablet PC pen gestures
• speech information
<Window.InputBindings>
<KeyBinding Key=“N"
Modifiers="Control"
Command="ApplicationCommands.New" />
</Window.InputBindings>
39 / 58
XAML
40. Handling Commands
• Execute and CanExecute methods do not contain
the application logic for the command
• Pass through the element tree until they encounter
an object with a CommandBinding
• CommandBinding contains the handlers for these
events
• attached to a specific object, such as the root Window of
the application or a control
• defines the scope of the binding
40 / 58
50. ToolTip Control
Creates a pop-up window that displays information
for an element in the interface.
Rendered View
50 / 58
51. ToolTip Control
XAML
51 / 58
<Button Command="ApplicationCommands.New">
<Image Source="../Resources/Icons/action_create_16xLG.png" />
<Button.ToolTip>
<TextBlock>Creates a new map.</TextBlock>
</Button.ToolTip>
</Button>
52. Assignment #2
1. Menu
1. Modify your MainWindow to use a Menu with two
MenuItems instead of Buttons.
2. Dock the menu to the Top of your MainWindow.
3. Use the WPF commands ApplicationCommands.Help
and ApplicationCommands.Close for the menu items
and bind these commands to Execute and CanExecute
methods in your MainWindow.xaml.cs.
4. In your MainWindow.xaml.cs, delegate the calls to
Execute and CanExecute to your controller
App.xaml.cs.
52 / 58
53. Assignment #2
2a. Map Model
1. Add a MapTileType class to your Model folder with
two properties Name and MovementCost.
2. Add a Vector2I struct to your Model folder with two
properties X and Y.
3. Add a MapTile class to your Model folder with two
properties Position and Type.
4. Add a Map class to your Model folder with an array
property Tiles.
53 / 58
54. Assignment #2
2b. Map Model
1. In App.xaml, define an event handler for the Startup
event of your application.
2. In App.xaml.cs, create a method that handles the
Startup event, setting up a dictionary that maps
strings to MapTileTypes:
1. Grass – Movement Cost 1
2. Desert – Movement Cost 3
3. Water – Movement Cost 5
54 / 58
55. Assignment #2
3. New Map
1. Create a new window called NewMapWindow.
1. Add TextBoxes that allow the user to specify the width and
height of the map to create.
2. Add an empty StackPanel that can be filled by code with radio
buttons for all map tile types.
3. Add a “Create New Map” button.
4. Dynamically fill the StackPanel with one RadioButton for each
map tile type defined in your controller.
2. Add a new MenuItem “New” to your MainWindow that
shows the NewMapWindow.
3. Handle the Clicked event of the “Create New Map” button
of the NewMapWindow, closing the window.
55 / 58
56. Assignment #2
4. Parsing and Error Handling
1. In App.xaml.cs, create a new map with the specified
dimensions and tiles when the user clicks “Create
New Map” in the NewMapWindow.
2. Show appropriate error messages when the user
specifies negative or invalid (e.g. contains letters) map
dimensions.
3. Ensure that the user always specifies a map tile type.
56 / 58
57. Assignment #2
5. Toolbar
1. Download the Visual Studio Image Library from
http://www.microsoft.com/en-
us/download/details.aspx?id=35825.
2. Add a ToolBar to your MainWindow with two buttons
for the New and Help commands, using the images of
your choice.
3. Add tooltips to both buttons.
57 / 58
58. References
• MSDN. WPF Controls by Category.
https://msdn.microsoft.com/en-
us/library/ms754204%28v=vs.100%29.aspx, April
2016.
• MSDN. Exceptions and Exception Handling.
http://msdn.microsoft.com/en-
us/library/ms173160(v=vs.110).aspx, April 2016.
• MSDN. WPF Commanding Overview.
https://msdn.microsoft.com/en-
us/library/ms752308%28v=vs.100%29.aspx, April
2016.
58 / 58
60. 5 Minute Review Session
• Which WPF layout control allows you to position its
children absolutely?
• Which other WPF layout panels do exist?
• Which C# keywords are related to signaling and
handling exceptions, and how do they work?
• Name a few exception best practices!
• Which WPF class allows you to easily show modal
dialog windows?
• Explain the difference between command, command
source, command target and command binding!
60 / 58