Chapter 11. Selecting WPF Controls

Windows Presentation Foundation (WPF) provides a whole new method for building user interfaces. Although it bears a superficial resemblance to Windows Forms, WPF provides new controls, a new event architecture, and a new foundation for building and interacting with properties.

WPF also provides tools for separating the user interface from the code behind the interface so that the two pieces can potentially be built by separate user interface designers and Visual Basic developers. It includes a new Extensible Application Markup Language (XAML, pronounced "zammel") that lets you build a user interface by using declarative statements rather than executable code. XAML lets you determine the size, position, and other properties of the WPF controls on a form. It lets you define styles that can be shared among many controls, and it lets you define transformations and animations that affect the controls.

As is the case in Windows Forms applications, controls play a central role in WPF applications. Different kinds of controls give information to the user (Label, StatusBar, TreeView, ListView, Image) and organize the information so that it's easy to understand (Border, StackPanel, DockPanel, TabControl). They enable the user to enter data (TextBox, TextBlock, ComboBox, PasswordBox), select options (RadioButton, CheckBox, ListBox), and control the application (Button, Menu, Slider).

To make an application as effective as possible, you should match controls with your application's needs. Though it is often possible to use many controls to perform a particular task, some controls usually work better than others. For example, you could display status information by changing a button's caption, but that's not really what buttons do best. A label in a status bar is usually a better way to give the user status information because the user will expect and understand it. Users generally don't expect to see status information in a button with changing text.

This chapter briefly describes the most common WPF controls so you can understand which controls work best for different purposes. To help you find the controls you need, the sections later in this chapter group controls by their general function. For example, if you need to display status to the user, look in the section "Providing Feedback."

I provide only brief descriptions of the WPF controls in this chapter, and some tips that can help you decide which control to use for different purposes. The following chapter, "Using WPF Controls," covers the controls in much greater detail, describing each control's most useful properties, methods, and events.

CONTROLS OVERVIEW

You can group WPF controls into several categories. Some of these correspond naturally to the purposes of Windows Forms controls. Other categories play a more important role in WPF than they do in Windows Forms applications.

In particular, WPF controls rely heavily on layout controls that arrange and organize the controls that they contain. Windows Forms developers often simply arrange controls on a form with their desired sizes and positions. A WPF application is more likely to arrange the controls in a hierarchy of StackPanel and Grid controls and let those controls arrange their contents.

The following sections describe the main categories of WPF controls. The example programs for this chapter, which are available on the book's web site, demonstrate many of the controls' basic uses.

CONTAINING AND ARRANGING CONTROLS

Layout controls determine the arrangement of the controls that they contain. For example, they may arrange controls vertically, horizontally, or in rows and columns.

The preferred style for WPF control arrangement is to make container controls determine the positions of their children and let the children take advantage of whatever space is allowed. This can be particularly useful for localized applications where you cannot easily predict how much space a control will need in a particular language.

For example, suppose a form contains a StackPanel control. The StackPanel contains several buttons that launch application dialogs. If you remove the buttons' Width properties, the buttons automatically size themselves to fit the StackPanel horizontally. Now if you need to make the buttons wider to hold text for a new language, you can simply widen the form. The StackPanel widens to fill the form and the buttons widen to fit the StackPanel.

Example program ResizingButtons, which is available for download on the book's web site, demonstrates buttons with fixed heights but widths that resize when their container resizes.

Note

In a Windows Forms application, you can achieve a similar effect by using Anchor and Dock properties.

Layout controls are also important because they can hold lots of other controls. Some of the WPF controls can hold only a single content item. For example, an Expander can hold only a single item. However, if you place another layout control such as a StackPanel inside the Expander, you can then place lots of other controls inside the StackPanel.

The following table briefly describes the WPF controls that are intended mainly to contain and arrange other controls.

CONTROL

PURPOSE

[a]
[b]

Border[a]

Provides a visible border or background to the contents.

BulletDecorator[b]

Contains two children. The first is used as a bullet and the second is aligned with the first. For example, you can use this to align bullet images next to labels. (See example program UseBulletDecorator, available for download on the book's web site.)

Canvas

Creates an area in which you can explicitly position children by specifying their Width, Height, Canvas.Left, and Canvas.Top properties. (See example program UseCanvas, available for download on the book's web site.)

DockPanel

Docks its children to its left, right, top, or bottom much as the Dock property does in a Windows Forms application. If the control's LastChildFill property is True, the control makes its last child control fill the remaining space. (See example program UseDockPanel, available for download on the book's web site.)

Expander[a]

Displays a header with an expanded/collapsed indicator. The user can click the header or indicator to expand or collapse the control's single content item. (See example program UseExpander, available for download on the book's web site.)

Grid

Displays children in rows and columns. This is somewhat similar to the Windows Forms TableLayoutPanel control. Grid is one of the most useful container controls.

GridSplitter

Allows the user to resize two rows or columns in a Grid control.

GridView

Displays data in columns within a ListView control.

GroupBox[a]

Displays a border and caption much as a Windows Forms GroupBox control does.

Panel

Panel is the parent class for Canvas, DockPanel, Grid, TabPanel, ToolbarOverflowPanel, UniformGrid, StackPanel, VirtualizingPanel, and WrapPanel. Usually you should use one of those classes instead of Panel, but you can use Panel to implement your own custom panel controls.

ScrollViewer[a]

Provides vertical and horizontal scroll bars for a single content element. (See example program UseScrollViewer, available for download on the book's web site.)

Separator

Separates two controls inside a layout control. (See example program UseSeparator, available for download on the book's web site.)

StackPanel

Arranges children in a single row or column. If there are too many controls, those that don't fit are clipped. StackPanel is one of the most useful container controls.

TabControl

Arranges children in tabs. TabItem controls contain the items that should be displayed in the tabs. (See example program UseTabControl, available for download on the book's web site.)

TabItem[a]

Holds the content for one TabControl tab.

Viewbox[a]

Stretches its single child to fill the Viewbox. The Stretch property determines whether the control stretches its child uniformly (without changing the width-to-height ratio). (See example program UseViewbox, available for download on the book's web site.)

VirtualizingStackPanel

Generates child items to hold items that can fit in the available area. For example, when working with a ListBox bound to a data source, the VirtualizingStackPanel generates only the items that will fit within the ListBox. If the control is not bound to a data source, this control behaves like a StackPanel.

WrapPanel

Arranges children in rows/columns depending on its Orientation property. When a row/column is full, the next child moves to a new row/column. This is similar to the Windows Forms FlowLayoutPanel control. (See example program UseWrapPanel, available for download on the book's web site.)

[a] This control can hold only a single child.

[b] This control should hold exactly two children. Controls with no footnote can hold any number of children.

Many of the layout controls have the ability to resize their children if you let them. For example, if you place a Button inside a Grid control's first row and column, by default the Button resizes when its row and column resize. The control's Margin property determines how far from the cell's edges the Button's edges lie.

If a child control explicitly defines its Width and Height properties, those properties override the parent's arrangement policy. For example, if you set Width and Height for a Button inside a Grid, the Button does not resize when its Grid cell does.

To get the effect that you want, consider how the control's Margin, Width, and Height properties interact with the parent layout control.

MAKING SELECTIONS

Selection controls enable the user to choose values. If you use them carefully, you can reduce the chances of the user making an invalid selection, so you can reduce the amount of error-handling code you need to write.

The following table briefly describes the WPF controls that allow the user to select choices.

CONTROL

PURPOSE

[a]

CheckBox

Lets the user select an item or not. Each CheckBox choice is independent of all others.

ComboBox

Displays items in a drop-down list. ComboBoxItem controls contain the items displayed in the list. (See example program UseComboBox, available for download on the book's web site.)

ComboBoxItem[a]

Holds the content for one ComboBox item.

ListBox

Displays items in a list. ListBoxItem controls contain the items displayed in the list. The control automatically displays scroll bars when needed. (See example program UseListBox, available for download on the book's web site.)

ListBoxItem[a]

Holds the content for one ListBox item.

RadioButton

Lets the user pick from among a set of options. If the user checks one RadioButton, all others with the same parent become unchecked. (See example program UseRadioButtons, available for download on the book's web site.)

ScrollBar

Allows the user to drag a "thumb" to select a numeric value. Usually scroll bars are used internally by other controls such as the ScrollViewer and your applications should use a Slider instead. (See example program UseScrollBar, available for download on the book's web site.)

Slider

Allows the user to drag a "thumb" to select a numeric value. Similar to the Windows Forms TrackBar control. (See example program UseSlider, available for download on the book's web site.)

[a] This control can hold only a single child.

ENTERING DATA

Sometimes, it is impractical to use the selection controls described in the previous section. For example, the user cannot reasonably enter biographical data or comments using a ComboBox or RadioButton. In those cases, you can provide a text control where the user can type information.

The following table briefly describes the WPF controls that allow the user to enter text.

CONTROL

PURPOSE

PasswordBox

Similar to a TextBox but displays a mask character instead of the characters that the user types. (See example program UsePasswordBox, available for download on the book's web site.)

RichTextBox

Similar to a TextBox but contains text in the form of a document object. See the section "Managing Documents" later in this chapter for more information on documents.

TextBox

Allows the user to enter simple text. Optionally can allow carriage returns and tabs, and can wrap text.

DISPLAYING DATA

These controls are used primarily to display data to the user. The following table briefly describes these WPF controls.

CONTROL

PURPOSE

Label

Displays non-editable text.

TextBlock

Displays more complex non-editable text. This control's contents can include inline tags to indicate special formatting. Tags can include AnchoredBlock, Bold, Hyperlink, InlineUIContainer, Italic, LineBreak, Run, Span, and Underline.

TreeView

Displays hierarchical data in a tree-like format similar to the directory display provided by Windows Explorer.

PROVIDING FEEDBACK

The following controls provide feedback to the user. Like the controls that display data in the previous section, these controls are intended to give information to the user and not interact with the user. The following table briefly describes these WPF controls.

CONTROL

PURPOSE

[a]

Popup

Displays content in a window above another control. Usually you can use the Tooltip and ContextMenu controls instead of a Popup. (See example program UsePopup, available for download on the book's web site.)

ProgressBar

Indicates the fraction of a long task that has been completed. Usually, the task is performed synchronously, so the user is left staring at the form while it completes. The ProgressBar lets the user know that the operation is not stuck. (See example program UseProgressBar, available for download on the book's web site.)

StatusBar

Displays a container at the bottom of the form where you can place controls holding status information. Though you can place anything inside a StatusBar, this control is intended to hold summary status information, not tools. Generally, menus, combo boxes, buttons, toolbars, and other controls that let the user manipulate the application do not belong in a SatusBar. (See example program UseStatusBar, available for download on the book's web site.)

StatusBarItem[a]

Holds the content for one StatusBar item.

ToolTip

Displays a tooltip. To give a control a simple textual tooltip, set its Tooltip property. Use the Tooltip control to build more complex tooltips. For example, a Tooltip control might contain a StackPanel that holds other controls. (See example program UseToolTip, available for download on the book's web site.)

[a] This control can hold only a single child.

INITIATING ACTION

Every kind of control responds to events, so every control can initiate an action. In practice, however, users only expect certain kinds of controls to perform actions. For example, they generally don't expect the application to launch into a time-consuming calculation when they double-click a label.

The following table summarizes controls that normally initiate action.

CONTROL

PURPOSE

[a]

Button[a]

Raises a Click event that the program can catch to perform an action. (See example program UseButtonRepeatButton, available for download on the book's web site.)

ContextMenu

Displays a context menu for other controls. Normally the ContextMenu contains MenuItem controls. (See example program UseMenuContextMenu, available for download on the book's web site.)

Menu

Displays a menu for the form. Normally, the Menu contains MenuItem controls representing the top-level menus. Those items contain other MenuItem controls representing commands. (See example program UseMenuContextMenu, available for download on the book's web site.)

MenuItem

Contains an item in a ContextMenu or Menu.

PrintDialog

Displays a standard Windows print dialog. You shouldn't place a PrintDialog on a window. Instead use code to build and display the PrintDialog. (See example program UsePrintDialog, available for download on the book's web site.)

RepeatButton[a]

Acts as a Button that raises its Click event repeatedly when it is pressed and held down. (See example program UseButtonRepeatButton, available for download on the book's web site.)

ToolBar

Contains items. Normally, the control sits across the top of the form and contains command items such as buttons and combo boxes. (See example program UseToolBar, available for download on the book's web site.)

ToolBarTray

Contains ToolBars and allows the user to drag them into new positions. (See example program UseToolBar, available for download on the book's web site.)

[a] This control can hold only a single child.

PRESENTING GRAPHICS AND MEDIA

Any control can display an image. The following XAML code makes an ImageBrush and then uses it to fill a Grid control's background:

<Window x:Class="Window1"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="FormImage"
 Height="300" Width="300">
   <Window.Resources>
       <ImageBrush ImageSource="smile.bmp" x:Key="brSmile" />
   </Window.Resources>
   <Grid Background="{StaticResource brSmile}">

   </Grid>
</Window>
                                                  
PRESENTING GRAPHICS AND MEDIA

Example program FormImage displays an image in a Grid control's background.

Though a Grid control can display an image or other graphic, its real purpose is to arrange other controls. The following table describes controls whose main purpose is to present graphics and media.

CONTROL

PURPOSE

Ellipse

Displays an ellipse.

Image

Displays a bitmap image, for example, from a .bmp, .jpg, or .png file. Can optionally stretch the image with or without distortion.

Line

Draws a line segment.

MediaElement

Presents audio and video. To let you control the media, it provides Play, Pause, and Stop methods, and Volume and SpeedRatio properties. (See example program UseMediaElement, available for download on the book's web site.)

Path

Draws a series of drawing instructions.

Polygon

Draws a closed polygon.

Polyline

Draws a series of connected line segments.

Rectangle

Draws a rectangle, optionally with rounded corners.

The shape drawing objects (Ellipse, Line, Path, Polygon, Polyline, and Rectangle) all provide Stroke, StrokeThickness, and Fill properties to let you control their appearance. Although these controls are primarily intended to draw simple (or not so simple) shapes, like any other control they provide a full assortment of events. For example, they provide an IsMouseOver property and a MouseUp event that you can use to make these objects behave like simple buttons.

Example program DrawingShapes, which is available for download on the book's web site, demonstrates several of these shape controls. Program EllipseClick, which is also available for download, uses triggers to change the color of an Ellipse when the mouse is over it, and displays a message when you click the Ellipse.

PROVIDING NAVIGATION

The Frame control provides support for navigation through external web sites or the application's pages. Use the control's Navigate method to display a web page or XAML page. The Frame provides back and forward arrows to let the user navigate through the pages visited.

Example program UseFrame, which is available for download on the book's web site, uses a Frame control to provide navigation between two Page objects.

MANAGING DOCUMENTS

WPF includes three different kinds of documents: flow documents, fixed documents, and XPS documents. These different kinds of documents provide support for high-end text viewing and printing.

The following table summarizes the controls that WPF provides for viewing these kinds of documents.

CONTROL

PURPOSE

DocumentViewer

Displays fixed documents page-by-page.

FlowDocumentPageViewer

Displays a flow document one page at a time. If the control is wide enough, it may display multiple columns although it still only displays one page at a time.

FlowDocumentReader

Displays flow documents in one of three modes. When in single page mode, it acts as a FlowDocumentReader. When in scrolling mode, it acts as a FlowDocumentScrollViewer. In book reading mode, it displays two pages side-by-side much as a real book does.

FlowDocumentScollViewer

Displays an entire flow document in a single long scrolling page and provides scroll bars to let the user move through the document.

DIGITAL INK

Digital ink controls provide support for stylus input from tablet PCs (where you use a plastic stylus similar to a pen to draw right on a tablet PC's touch screen). Normally you would only use digital ink in a tablet PC application where the user is expected to enter data by drawing on the screen with a stylus. These applications usually provide text recognition to understand what the user is writing. They also use the stylus to perform the same operations they would perform with the mouse on a desktop system. For example, they let you tap to click buttons, and tap and drag to move items. For more information on tablet PCs and mobile PC development, see msdn.microsoft.com/windows/aa905027.aspx.

Though ink controls are most useful for tablet PCs, WPF includes two ink controls that you can use in any Visual Basic application.

CONTROL

PURPOSE

InkCanvas

Displays or captures ink strokes.

InkPresenter

Displays ink strokes.

SUMMARY

Controls are the link between the user and the application. They allow the application to give information to the user and they allow the user to control the application.

This chapter briefly describes the WPF controls grouped by category. You can use the categories to help you decide which controls to use. If the user must select an item, consider the controls in the "Making Selections" section. If the application needs to display status information, look at the controls in the "Providing Feedback" section.

This chapter gives only a brief introduction to the WPF controls and provides some hints about each control's purpose. Chapter 12, "Using WPF Controls," describes the controls in greater detail. It explains the most important properties, methods, and events provided by the most useful WPF controls.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.102.178