Tool Development 02 - Advanced WPF Controls

Preview:

DESCRIPTION

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.

Citation preview

Tool DevelopmentChapter 02: Advanced WPF Controls

Nick Prühs

June 5, 2014

5 Minute Review Session

• Why should you make tools as early as possible?

• Name a few important requirements for all tools!

• What is Model-View-Controller?

• What is the basic architecture of a WPF application?

• How are C# events used?

• How do you define the entrance point of a WPF application?

• How are the controls arranged by the WPF layout engine?

• How do you bind data to a WPF control?

2 / 58

Assignment Solution #1

DEMO

3 / 58

Objectives

• To understand the different layouting mechanismsof 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

4 / 58

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.

5 / 58

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

6 / 58

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>

7 / 58

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

8 / 58

DockPanel Control

XAML

<DockPanel>

<Border Background="SkyBlue" DockPanel.Dock="Top">

<TextBlock>Dock = "Top"</TextBlock>

</Border>

<Border Height="50" Background="LemonChiffon" DockPanel.Dock="Top">

<TextBlock>Dock = "Top"</TextBlock>

</Border>

<Border Background="PaleGreen" DockPanel.Dock="Left">

<TextBlock>Dock = "Left"</TextBlock>

</Border>

<Border Background="White">

<TextBlock>This content will "Fill" the remaining space.</TextBlock>

</Border>

</DockPanel>

9 / 58

Grid 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

10 / 58

Grid Control

XAML

11 / 58

<Grid VerticalAlignment="Top" HorizontalAlignment="Left">

<Grid.ColumnDefinitions>

<ColumnDefinition />

<ColumnDefinition />

<ColumnDefinition />

</Grid.ColumnDefinitions>

<Grid.RowDefinitions>

<RowDefinition />

<RowDefinition />

</Grid.RowDefinitions>

<!-- ... -->

Grid Control

XAML (Cont.)

12 / 58

<!-- ... -->

<TextBlock Grid.Row="0" Grid.Column="0" Margin="5">Quarter 1</TextBlock>

<TextBlock Grid.Row="0" Grid.Column="1" Margin="5">Quarter 2</TextBlock>

<TextBlock Grid.Row="0" Grid.Column="2" Margin="5">Quarter 3</TextBlock>

<TextBlock Grid.Row="1" Grid.Column="0" TextAlignment="Right">50000</TextBlock>

<TextBlock Grid.Row="1" Grid.Column="1" TextAlignment="Right">100000</TextBlock>

<TextBlock Grid.Row="1" Grid.Column="2" TextAlignment="Right">150000</TextBlock>

</Grid>

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

13 / 58

ScrollViewer Control

XAML

14 / 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>

StackPanel Control

Allows you to stack elements in a specified direction.

Rendered View

15 / 58

StackPanel Control

XAML

16 / 58

<StackPanel>

<Border Background="SkyBlue">

<TextBlock>Stacked Item #1</TextBlock>

</Border>

<Border Background="LightGoldenRodYellow">

<TextBlock>Stacked Item #2</TextBlock>

</Border>

<Border Background="PaleGreen">

<TextBlock>Stacked Item #3</TextBlock>

</Border>

</StackPanel>

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

17 / 58

WrapPanel Control

XAML

18 / 58

<WrapPanel Background="LightBlue" Width="200" Height="100">

<Button Width="200">Button 1</Button>

<Button>Button 2</Button>

<Button>Button 3</Button>

<Button>Button 4</Button>

</WrapPanel>

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!

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

Throwing Exceptions

• Exceptions are created by using the throw keyword.

if (width <= 0)

{

throw new ArgumentOutOfRangeException("width", "Width must be positive.");

}

21 / 58

C#

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#

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

Handling Exceptions

24 / 58

Unhandled exception reported by Microsoft Visual Studio 2012

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

Gotcha!

Never use empty catch blocks!

26 / 58

Common Exceptions

• Thrown by your application or the framework• InvalidOperationException

• ArgumentException

• ArgumentNullException

• ArgumentOutOfRangeException

• Thrown by the CLR• NullReferenceException

• IndexOfOutRangeException

• StackOverflowException

• OutOfMemoryException

27 / 58

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#

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

MessageBox Usage

• Parameters• Text

• Title bar caption

• Button(s)

• Icon

• Return Value• Result

30 / 58

MessageBox Parameter Types

• Buttons• OK

• OKCancel

• YesNo

• YesNoCancel

• Icon• Error

• Question

• Warning

• Information

31 / 58

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

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

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

WPF Command Example

• Command: Paste

• Command source: MenuItem

• Command target: Textbox

• Command binding: Supplied by Textbox control

35 / 58

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

Common WPF Commands

• MediaCommands• Play, Pause, NextTrack, IncreaseVolume

• ApplicationCommands• New, Open, Copy, Undo

• NavigationCommands• NextPage, Refresh, Search, Zoom

• ComponentCommands• MoveDown, ScrollPageDown

• EditionCommands• Delete, EnterLineBreak, ToggleItalic

37 / 58

Command Sources

• Implementations of ICommandSource• e.g. MenuItem, Button

<MenuItem Command="ApplicationCommands.New"/>

38 / 58

XAML

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

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

Handling Commands Example

XAML

41 / 58

<Window.CommandBindings>

<CommandBinding Command="ApplicationCommands.New"

Executed="CommandExecutedNew"

CanExecute="CommandCanExecuteNew"/>

</Window.CommandBindings>

private void CommandExecutedNew(object sender, ExecutedRoutedEventArgs e)

{

this.controller.ExecuteNew();

}

private void CommandCanExecuteNew(object sender, CanExecuteRoutedEventArgs e)

{

e.CanExecute = this.controller.CanExecuteNew();

}

C#

Menu Control

Organizes elements associated with commands and event handlers in a hierarchical order.

Rendered View

42 / 58

Menu Control

XAML

43 / 58

<DockPanel>

<Menu DockPanel.Dock="Top">

<MenuItem Header="_File">

<MenuItem Command="ApplicationCommands.New"/>

<MenuItem Command="ApplicationCommands.Help"/>

<MenuItem Command="ApplicationCommands.Close"/>

</MenuItem>

</Menu>

</DockPanel>

Toolbar Control

Container for a group of commands or controls.

Rendered View

44 / 58

Toolbar Control

XAML

45 / 58

<ToolBarTray DockPanel.Dock="Top">

<ToolBar>

<Button Command="ApplicationCommands.New">

<Image Source="../Resources/Icons/action_create_16xLG.png" />

</Button>

<Separator/>

<Button Command="ApplicationCommands.Help">

<Image Source="../Resources/Icons/Symbols_Help_and_inclusive_16xLG.png" />

</Button>

</ToolBar>

</ToolBarTray>

StatusBar Control

Displays items and information in a horizontal bar in an application window.

Rendered View

46 / 58

StatusBar Control

XAML

47 / 58

<StatusBar VerticalAlignment="Bottom" Background="Beige" >

<StatusBarItem>

<TextBlock>Opening File...</TextBlock>

</StatusBarItem>

</StatusBar>

ProgressBar Control

Indicates the progress of an operation.

Rendered View

48 / 58

ProgressBar Control

XAML

49 / 58

<StatusBar VerticalAlignment="Bottom" Background="Beige" >

<StatusBarItem>

<ProgressBar Name="ProgressBar" Width="100" Height="20" Value="87" />

</StatusBarItem>

<StatusBarItem>

<TextBlock>

Opening File...

</TextBlock>

</StatusBarItem>

<StatusBarItem>

<TextBlock>

(87%)

</TextBlock>

</StatusBarItem>

</StatusBar>

ToolTip Control

Creates a pop-up window that displays information for an element in the interface.

Rendered View

50 / 58

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>

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 CanExecutemethods in your MainWindow.xaml.cs.

4. In your MainWindow.xaml.cs, delegate the calls toExecute and CanExecute to your controllerApp.xaml.cs.

52 / 58

Assignment #2

2. 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

53 / 58

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.

54 / 58

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.

55 / 58

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 buttonsfor the New and Help commands, using the images ofyour choice.

3. Add tooltips to both buttons.

56 / 58

References

• MSDN. WPF Controls by Category. http://msdn.microsoft.com/en-us/library/ms754204%28v=vs.110%29.aspx, June 2014.

• MSDN. Exceptions and Exception Handling. http://msdn.microsoft.com/en-us/library/ms173160.aspx, June 2014.

• MSDN. WPF Commanding Overview. http://msdn.microsoft.com/en-us/library/ms752308%28v=vs.110%29.aspx, June 2014.

57 / 58

Thank you for your attention!

Contact

Mail

dev@npruehs.de

Blog

http://www.npruehs.de

Twitter

@npruehs

Github

https://github.com/npruehs

58 / 58

Recommended