SlideShare a Scribd company logo
Controls
CHAPTER 8.2
What you will learn in this chapter
 Content controls. These controls can contain nested elements, giving them nearly
unlimited display abilities. They include the Label, Button, and ToolTip classes.
 Headered content controls. These are content controls that allow you to add a
main section of content and a separate title portion. They are usually intended to
wrap larger blocks of user interface. They include the TabItem, GroupBox, and
Expander classes.
 Text controls. This is the small set of controls that allow users to enter input. The text
controls support ordinary text (the TextBox), passwords (the PasswordBox).
 List controls. These controls show collections of items in a list. They include the
ListBox and ComboBox classes. Range-based controls. These controls have just one
thing in common: a Value property that can be set to any number in a prescribed
range. Examples include the Slider and ProgressBar classes.
 Date controls. This category includes two controls that allow users to select dates:
the Calendar and DatePicker.
What you will learn in this chapter
 ListView. The ListView derives from the plain-vanilla ListBox. It adds support for
column-based display and the ability to switch quickly between different “views,”
or display modes, without requiring you to rebind the data and rebuild the list.
 TreeView. The TreeView is a hierarchical container, which means you can create a
multilayered data display. For example, you could create a TreeView that shows
category groups in its first level and shows the related products under each
category node.
 DataGrid. The DataGrid is WPF’s most full-featured data display tool. It divides your
data into a grid of columns and rows, like the ListView, but has additional
formatting features (such as the ability to freeze columns and style individual rows),
and it supports in-place data editing.
What you will learn in this chapter
 Menus. They’re one of the oldest user interface controls, and they’ve changed
surprisingly little in the past two decades. WPF includes solid, straightforward
support for main menus and popup context menus.
 Toolbars and status bars. They decorate the top and bottom of countless
applications—sometimes when they aren’t even needed. WPF supports both
controls with its customary flexibility, allowing you to insert virtually any control
inside. However, the WPF toolbars and status bars don’t have many frills. They
support overflow menus, but they don’t provide floating and docking capability.
 Ribbons. With only a little more effort, you can add an Office-style ribbon to the
top of your application window. It requires a separate (free) download, but you’ll
get some valuable built-in features, such as configurable resizing. You’ll also get an
Office-style menu feature to match.
The ListView is a specialized list class that’s designed for displaying different views
of the same data. The ListView is particularly useful if you need to build a multicolumn
view that displays several pieces of information about each data item.
The ListView derives from the ListBox class and extends it with a single detail: the
View property. The View property is yet another extensibility point for creating rich list
displays. If you don’t set the View property, the ListView behaves just like its lesser-
powered ancestor, the ListBox.
View property points to an instance of any class that derives from ViewBase
(which is an abstract class). The ViewBase class is surprisingly simple; in fact, it’s little
more than a package that binds together two styles. One style applies to the ListView
control (and is referenced by the DefaultStyleKey property), and the other style
applies to the items in the ListView (and is referenced by
theZItemContainerDefaultStyleKey property). The DefaultStyleKey and
ItemContainerDefaultStyleKey properties don’t actually provide the style; instead,
they return a ResourceKey object that points to it.
THE LISTVIEW
View property is a useful abstraction of its advantages:
 Reusable views. The ListView separates all the view-specific details into one object.
That makes it easier to create views that are data-independent and can be used
on more than one list.
 Multiple views. The separation between the ListView control and the View objects
also makes it easier to switch between multiple views with the same list. (For
example, you use this technique in Windows Explorer to get a different perspective
on your files and folders.) You could build the same feature by dynamically
changing templates and styles, but it’s easier to have just one object that
encapsulates all the view details.
 Better organization. The view object wraps two styles: one for the root ListView
control and one that applies to the individual items in the list. Because these styles
are packaged together, it’s clear that these two pieces are related and may share
certain details and interdependencies. For example, this makes a lot of sense for a
column-based ListView, because it needs to keep its column headers and column
data lined up.
THE LISTVIEW
Creating Columns with the GridView
The GridView is a class that derives from ViewBase and
represents a list view with multiple columns. It define those
columns by adding GridViewColumn objects to the
GridView.Columns collection.
Figure 22-1 shows a straightforward example with three
columns of information about a product.
THE LISTVIEW
Creating Columns with the GridView
THE LISTVIEW
Resizing Columns
For more micromanaged control over
column size, you can set a specific width
when you declare the column:
THE LISTVIEW
Cell Templates
The GridViewColumn.DisplayMemberBinding property isn’t the only option
for showing data in a cell. Your other choice is the CellTemplate property,
which takes a data template. This is exactly like the data templates you
learned, except it applies to just one column. If you’re ambitious, you can give
each column its own data template.
Cell templates are a key piece of the puzzle when customizing the
GridView. One feature that they allow is text wrapping. Ordinarily, the text in a
column is wrapped in a single-line TextBlock. However, it’s easy to change this
detail using a data template of your own devising:
THE LISTVIEW
Cell Templates
THE LISTVIEW
Creating Custom View
If the GridView doesn’t meet your needs, you can create your own view to extend
the ListView’s capabilities. Unfortunately, it’s far from straightforward.
To understand the problem, you need to know a little more about the way a view
works. Views do their work by overriding two protected properties: DefaultStyleKey
and ItemContainerDefaultKeyStyle. Each property returns a specialized object called
a ResourceKey, which points to a style that you’ve defined in XAML. The
DefaultStyleKey property points to the style that should be applied to configure the
overall ListView. The temContainer.DefaultKeyStyle property points to the style that
should be used to configure each ListViewItem in the ListView. Although these styles
are free to tweak any property, they usually do their work by replacing the
ControlTemplate that’s used for the ListView and the DataTemplate that’s used for
each ListViewItem.
THE LISTVIEW
Creating Custom View
The following example shows you how to create a grid that can be switched
seamlessly from one view to another. The grid begins in the familiar column-
separated view but also supports two tiled image views, as shown in Figure 22-3
and Figure 22-4.
THE LISTVIEW
Using the Listview
C# Code
XAML Code
THE LISTVIEW
<ListView x:Name="lstView" HorizontalAlignment="Left" Height="153" VerticalAlignment="Top" Width="465">
<ListView.View>
<GridView>
<GridView.ColumnHeaderContextMenu>
<ContextMenu/>
</GridView.ColumnHeaderContextMenu>
<GridViewColumn Header="Firstname" Width="150" DisplayMemberBinding="{Binding Path=fName}"/>
<GridViewColumn Header="Middlename" Width="150" DisplayMemberBinding="{Binding Path=mName}"/>
<GridViewColumn Header="Lastname" Width="150" DisplayMemberBinding="{Binding Path=lName}"/>
<GridViewColumn Header="Extension" Width="50" DisplayMemberBinding="{Binding Path=eName}"/>
</GridView>
</ListView.View>
private void button_Click(object sender, RoutedEventArgs e) {
List<Person> items = new List<Person>();
items.Add(new Person() { fName = firstnameTextBox .Text ,
mName = middlenameTextBox .Text ,
lName = lastnameTextBox .Text ,
eName = extensionnameTextBox.Text });
lstView.Items.Add(items); }
public class Person {
public string fName { get; set; }
public string mName { get; set; }
public string lName { get; set; }
public string eName { get; set; } }
Using the Listview
THE LISTVIEW
The TreeView is a Windows staple, and it’s a common ingredient
in everything from the Windows Explorer file browser to the .NET
help library. WPF’s implementation of the TreeView is impressive,
because it has full support for data binding.
The TreeView is, at its heart, a specialized ItemsControl that hosts
TreeViewItem objects. But unlike the ListViewItem, the TreeViewItem
is not a content control. Instead, each TreeViewItem is a separate
ItemsControl, with the ability to hold more TreeViewItem objects.
This flexibility allows you to create a deeply layered data display.
THE TREEVIEW
Here’s the skeleton of a very basic TreeView, which is declared
entirely in XAML markup:
THE TREEVIEW
Here’s the skeleton of a very basic TreeView, which is declared
entirely in properties:
THE TREEVIEW
Binding a DataSet to a TreeView
You can also use a TreeView to show a multilayered DataSet—one that has
relationships linking one DataTable to another.
For example, here’s a code routine that creates a DataSet, fills it with a
table of products and a separate table of categories, and links the two tables
together with a DataRelation object:
THE TREEVIEW
DataGrid is a data-display control that takes the information from a
collection of objects and renders it in a grid of rows and cells. Each row
corresponds to a separate object, and each column corresponds to a
property in that object.
The DataGrid adds much-needed versatility for dealing with data in WPF. Its
column-based model gives it remarkable formatting flexibility. Its selection
model allows you to choose whether users can select a row, multiple rows, or
some combination of cells. Its editing support is powerful enough that you can
use the DataGrid as an all-in-one data editor for simple and complex data.
THE DATAGRID
To create a quick-and-dirty DataGrid, you can use automatic column
generation. To do so, you need to set the AutoGenerateColumns property to
true (which is the default value):
THE DATAGRID
<DataGrid x:Name="gridPerson" AutoGenerateColumns="True">
</DataGrid>
To create a quick-and-dirty DataGrid, you can use automatic column
generation. To do so, you need to set the AutoGenerateColumns property to
true (which is the default value):
XAML Code
C# Code
THE DATAGRID
private void Window Loaded(object sender, RoutedEventArgs e)
{
PersonalInformationDataSetTableAdapters.Person_tabTableAdapter pA;
pA = new PersonalInformationDataSetTableAdapters.Person_tabTableAdapter();
PersonalInformationDataSet.Person_tabDataTable pT;
pT = new PersonalInformationDataSet.Person_tabDataTable();
pA.Fill(pT);
dtgPersonInfo.DataContext = pT;
}
DataGrid Name=“dtgPersonInfo" AutoGenerateColumns="True"
ItemsSource="{Binding}" Grid.ColumnSpan="4" Margin="0,45,0,-205" Grid.Row="2"/>
WPF provides two menu controls: Menu (for main menus) and
ContextMenu (for popup menus that are attached to other
elements). Like all the WPF classes, WPF performs the rendering for
the Menu and ContextMenu controls. That means these controls
aren’t simple Win32 wrappers, and they have the flexibility to be
used in some unusual ways.
MENUS
The Menu Class
WPF doesn’t make any assumption
about where a stand-alone menu should
be placed. Ordinarily, you’ll dock it at
the top of your window using a
DockPanel or the top row of a Grid, and
you’ll stretch it across the entire width of
your window. However, you can place a
menu anywhere, even alongside other
controls (as shown in Figure 25-1).
Furthermore, you can add as many
menus in a window as you want.
Although it might not make much sense,
you have the ability to stack menu bars
or scatter them throughout your user
MENUS
Menu Items
Menus are composed of MenuItem
objects and Separator objects. The
MenuItem class derives from
HeaderedItemsControl, because
each menu item has a header (which
contains the text for that item) and
can hold a collection of MenuItem
objects (which represents a submenu).
The Separator simply displays a
horizontal line separating menu items.
Here’s a straightforward
combination of MenuItem objects that
creates the rudimentary menu
structure shown in Figure 25-3:
MENUS
Setting menu item in
XAML
Menu Items
MENUS
Setting menu item in
Properties
Toolbars and status bars are two well-worn staples of the
Windows world. Both are specialized containers that hold a
collection of items. Traditionally, a toolbar holds buttons, and a
status bar consists primarily of text and other noninteractive
indicators (like a progress bar). However, both toolbars and status
bars are used with a variety of different controls.
In Windows Forms, toolbars and status bars have their own
content model. Although it’s still possible to place arbitrary controls
inside a toolbar and status bar using a wrapper, the process isn’t
seamless. The WPF toolbar and status bar don’t have this limitation.
They support the WPF content model, allowing you to add any
element to a toolbar or status bar and giving you unparalleled
flexibility.
TOOLBARS AND STATUS BARS
The Toolbar
A typical WPF ToolBar is filled with Button, ComboBox, CheckBox, RadioButton, and
Separator objects. Because these elements are all content controls (except for the
Separator), you can place text and image content inside. Although you can use
other elements, such as Label and Image to put noninteractive elements into the
ToolBar, the effect is often confusing.
To demonstrate what this looks like, consider the simple markup shown here:
TOOLBARS AND STATUS BARS
Figure 25-5 shows this toolbar in action, with two CheckBox
controls in the checked state and the drop-down list on
display.
The Toolbar
To demonstrate in Designer shown here:
TOOLBARS AND STATUS BARS
The ToolbarTray
The ToolBarTray makes it easier for toolbars to share the same
row, or band. You can configure the ToolBarTray so that toolbars
share a band, while others are placed on other bands. The
ToolBarTray provides the shaded background behind the entire
ToolBar area. But most important, the ToolBarTray adds support for
toolbar drag-and-drop functionality. Unless you set the
ToolBarTray.IsLocked property to true, the user can rearrange your
toolbars in a ToolBar tray by clicking the grip at the left side.
Toolbars can be repositioned in the same band or moved to a
different band.
TOOLBARS AND STATUS BARS
The ToolbarTray
Here’s some sample markup that creates several toolbars in a ToolBarTray.
Figure 25-7 shows the result
TOOLBARS AND STATUS BARS
The ToolbarTray
Here’s some sample designer that creates several toolbars in a ToolBarTray. Figure 25-7
shows the result
TOOLBARS AND STATUS BARS
The Statusbar
The StatusBar doesn’t work very well if you want to use one of
the ButtonBase-derived elements or the ComboBox. It doesn’t
override the styles of any of these controls, so they look out of
place in the status bar. If you need to create a status bar that
includes these controls, you might consider docking an ordinary
ToolBar control to the bottom of your window. It’s probably as a
result of this general lack of features that the StatusBar is found in
the System.Windows.Controls.Primitives namespace rather than in
the more mainstream System.Windows.Controls namespace where
the ToolBar control exists.
TOOLBARS AND STATUS BARS
The Statusbar
One way to get proportionally or right-aligned items is to use a Grid for your layout
container. The only trick is that you must wrap the child element in a StatusBarItem
object in order to set the Grid.Column property appropriately. Here’s an example that
uses a Grid to place one TextBlock on the left side of a StatusBar and another on the
right side:
TOOLBARS AND STATUS BARS
The Statusbar
Setting in designer.
TOOLBARS AND STATUS BARS
With the ribbon, Microsoft found itself faced with a familiar dilemma. To
improve the productivity and consistency of all Windows applications,
Microsoft wanted to encourage every application to adopt the ribbon. But
because Microsoft also wanted to keep its competitive edge, it wasn’t in a
rush to release the APIs that would make that possible. After all, Microsoft spent
thousands of hours of research and development in perfecting its version of
the ribbon, so it’s no surprise that the company took a few years to enjoy the
result.
Fortunately, the wait has ended, and Microsoft has now made a version of
the ribbon available to WPF developers. The good news is that it’s completely
free and respectably full-featured, including rich tooltips, drop-down buttons,
dialog launchers, a quick access toolbar, and configurable resizing.
RIBBONS
The ribbon control isn’t included with the .NET Framework. Instead, it’s
available as a separate download, which is considered to be a “preview”
version at the time of this writing. You can download it from the Office UI
Licensing website at http://msdn.microsoft.com/officeui (look for a “License
the Office UI” link). Don’t be intimidated about the terminology—licensing
simply means providing your contact information and accepting a one-page
agreement that states that you will follow the Office UI design guidelines. (In
other words, Microsoft doesn’t want you using the ribbon control if you aren’t
using it right.) You can find ribbon guidelines and best practices at
http://tinyurl.com/4dsbef.
Once you’ve downloaded the ribbon, you’ll get a single compiled class
library assembly, named RibbonControlsLibrary.dll. To start using the ribbon,
add a reference to this library in any WPF application, and keep reading.
RIBBONS
Adding the Ribbon
As with any control that’s not a part of the core WPF libraries, you need to
map the control assembly to an XML prefix before you can use it:
<Window x:Class="RibbonTest.MainWindow" ... xmlns:r=
"clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary">
You can then add an instance of the Ribbon control anywhere in your
window:
<r:Ribbon>
</r:Ribbon>
RIBBONS
Adding the Ribbon
The RibbonControlsLibrary.dll assembly addresses this issue by including the
RibbonWindow—a class that derives from Window and integrates more
seamlessly with the ribbon. Figure 25-8 compares the difference.
RIBBONS
Adding the Ribbon
Here’s a basic skeleton for a custom window that derives from
RibbonWindow and places the ribbon at the top, while reserving the second
row of a Grid for the actual window content.
RIBBONS
Syling the Ribbon
There’s one more detail to consider before
you start filling the ribbon with buttons.
Ordinarily, the ribbon is styled to look like the
ribbon in Windows 7 applications (like Paint).
That means the application menu button is a
square that sits just under the window border
and quick access toolbar, and the background
of the ribbon blends into the background of the
window frame. Your other choice is to use Office
2007 styling, which applies a more dramatic
background color, turns the application menu
button into a large circle, and moves it up to the
top-left corner of the window. Figure 25-9 shows
the difference.
RIBBONS
Commands
The ribbon is built around the concept of commands. These commands
power all parts of the ribbon, including its buttons, the application menu, and
the quick access toolbar.
Unlike WPF’s standard menu and toolbars, the ribbon doesn’t allow you to
intercept Click events from its constituent controls. Instead, it forces you to use
a higher-level design and to wire the ribbon controls to custom command
objects.
To support this system, the ribbon includes a new class that derives from
RoutedCommand, called RibbonCommand. The advantage of this design is
that it allows the ribbon to supply richer command functionality. (As you
learned in Chapter 9, WPF’s basic command model is pretty modest.) The
disadvantage of this design is that it means you can’t use any custom classes
you may have already derived from RoutedCommand with the ribbon.
RIBBONS
Commands
Table 25-1 lists the
properties that the
RibbonCommand adds to
the base RoutedCommand.
RIBBONS
The Applpication Menu
The easiest way to get started with the ribbon is to fill the application menu.
The application menu is based on two straightforward classes:
RibbonApplicationMenu (which derives from MenuBase) and RibbonMenuItem
(which derives from MenuItem). This establishes a pattern you’ll see throughout
this section—the ribbon takes the base WPF control class and derives more
specialized versions. From a purist point of view, this isn’t ideal. The ToolBar and
StatusBar have a far cleaner model, because they’re able to work with
standard WPF controls, which they simply restyle.
RIBBONS
The Applpication Menu
To create a menu, you create a new RibbonApplicationMenu object and
use that to set the Ribbon.ApplicationMenu property. As you probably already
expect, the RibbonApplicationMenu includes a collection of
RibbonApplicationMenuItem objects, each of which represents a separate
clickable menu item.
Here’s a basic example outline that creates an application menu with three
menu items:
RIBBONS
The Applpication Menu
To configure each command, you
simply need to supply a
RibbonCommand object. This object
specifies the menu text (through the
LabelTitle property), an optional tooltip
(using the ToolTipTitle,
ToolTipDescription, and so on), an
optional image (LargeImageSource),
and the event handler that should be
triggered when the menu item is clicked
(Executed). As you learned in Chapter
9, you can also handle the CanExecute
event to configure whether a
command should be enabled or
disabled.
Here’s an example that fills in the
three commands (but leaves out the
optional tooltip properties):
RIBBONS
The Applpication Menu
The top-level RibbonApplicationMenu
object also needs a RibbonCommand object,
even though it isn’t used to trigger a command!
That’s because a few of the other properties,
such as the tooltip properties and the image
properties (which set the image that appears in
the application menu button). If you’re using
the default Windows 7 style, you need to set the
SmallImage property, while the Office 2007
styles have a large application button and
need to have the LargeImageSource property.
It’s also worth noting that any
RibbonApplicationMenuItem can hold more
RibbonApplicationMenuItem objects to create
a submenu. The submenu is displayed in the
second column of the menu, as shown in Figure
25-10.
RIBBONS
The Applpication Menu
When creating a submenu, you can set the RibbonCommand.LabelTitle property
of the containing RibbonApplicationMenuItem object to add a title that will be shown
over the submenu, as in Figure 25- 10. Here’s the markup you need:
RIBBONS
Tabs, Groups and Buttons
The ribbon uses the same model to fill its
toolbar tabs as it does to fill its application
menu, just with a few extra layers.
First, the ribbon holds a collection of tabs.
In turn, each tab holds one or more groups,
which is an outlined, titled, boxlike section of
the ribbon. Lastly, each group holds one or
more ribbon controls. Figure 25-11 shows this
arrangement.
RIBBONS
Ribbon Sizing
One of the ribbon’s most remarkable
features is its ability to resize itself to fit the
width of the window by reducing and
rearranging the buttons in each groups.
Figure 25-12 illustrates this process with a
ribbon that has three copies of the File group.
The first is fully expanded, the second is
partially collapsed, and the second is
completely collapsed. (It’s worth noting that in
order to create this example, the ribbon must
be explicitly configured to not collapse the
first group. Otherwise, it will always try to
partially collapse every group before it fully
collapses any group.)
RIBBONS
Ribbon Sizing
To take control of group resizing, you
need to define multiple
RibbonGroupSizeDefinition objects and
order them from largest to smallest in a
RibbonGroupSizeDefinitionCollection. As the
group is collapsed, the ribbon can then
switch from one layout to the next to reclaim
more space, while keeping the layout you
want (and ensuring that the controls you
think are most important remain visible).
Usually, you’ll place the
RibbonGroupSizeDefinitionCollection in the
Ribbon.Resources section, so you can reuse
the same sequences of templates for more
RIBBONS
The Quick Access Toolbar
The final ingredient that you’ll consider in the ribbon is the quick
access toolbar (or QAT). It’s a narrow strip of commonly used
buttons that sits either just above or just below the rest of the
ribbon, depending on user selection.
The QAT is represented by the QuickAccessToolBar object, which
holds a series of RibbonButton objects. When defining the
RibbonCommand for these objects, you need only supply the
tooltip text and small image, because text labels and large images
are never shown.
RIBBONS
The Quick Access Toolbar
The only new detail in the QAT is the customize menu that appears
when you click the drop-down arrow off the far right of it (Figure 25-13). You
can use this menu to let users customize the commands that appear in the
QAT. Or, you can disable the customize menu by setting
QuickAccessToolBar.CanUserCustomize to false.
RIBBONS

More Related Content

DOC
Form part1
PPTX
Relational Database Management System
PDF
Collectn framework
PDF
Collectn framework copy
ODP
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
PPT
Ap Power Point Chpt9
PDF
GridView,Recycler view, API, SQLITE& NetworkRequest.pdf
PPT
Chapter12 (1)
Form part1
Relational Database Management System
Collectn framework
Collectn framework copy
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Ap Power Point Chpt9
GridView,Recycler view, API, SQLITE& NetworkRequest.pdf
Chapter12 (1)

Similar to Ch7.2-Controls for Programm 001-193819qk (20)

PDF
Lab2-android
PDF
Grid View- GridView is a ViewGroup that displays items in a two d.pdf
PPTX
Java Collection Framework 2nd year B.Tech.pptx
PPTX
Android Training (AdapterView & Adapter)
PPT
Hello Android
PPTX
Ado.net xml data serialization
PPTX
MS SQL SERVER: SSIS and data mining
PPTX
MS SQL SERVER: SSIS and data mining
PPTX
Codds rules & keys
PDF
Murach: How to transfer data from controllers
PDF
Day 8: Dealing with Lists and ListViews
PDF
Learn about dot net attributes
PPT
PPTX
codd rules of dbms given by E F codd who is called father of dbms
PPTX
Sql server ___________session_16(views)
PPTX
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
PPT
Olap
PPTX
Designing and Creating Views, Inline Functions, and Synonyms
PDF
React table tutorial use filter (part 2)
PDF
Day 8: Dealing with Lists and ListViews
Lab2-android
Grid View- GridView is a ViewGroup that displays items in a two d.pdf
Java Collection Framework 2nd year B.Tech.pptx
Android Training (AdapterView & Adapter)
Hello Android
Ado.net xml data serialization
MS SQL SERVER: SSIS and data mining
MS SQL SERVER: SSIS and data mining
Codds rules & keys
Murach: How to transfer data from controllers
Day 8: Dealing with Lists and ListViews
Learn about dot net attributes
codd rules of dbms given by E F codd who is called father of dbms
Sql server ___________session_16(views)
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Olap
Designing and Creating Views, Inline Functions, and Synonyms
React table tutorial use filter (part 2)
Day 8: Dealing with Lists and ListViews
Ad

Recently uploaded (20)

PPTX
TLE Review Electricity (Electricity).pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
August Patch Tuesday
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Spectroscopy.pptx food analysis technology
TLE Review Electricity (Electricity).pptx
A Presentation on Artificial Intelligence
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Per capita expenditure prediction using model stacking based on satellite ima...
MIND Revenue Release Quarter 2 2025 Press Release
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
NewMind AI Weekly Chronicles - August'25-Week II
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Assigned Numbers - 2025 - Bluetooth® Document
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
August Patch Tuesday
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
cloud_computing_Infrastucture_as_cloud_p
Network Security Unit 5.pdf for BCA BBA.
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Spectroscopy.pptx food analysis technology
Ad

Ch7.2-Controls for Programm 001-193819qk

  • 2. What you will learn in this chapter  Content controls. These controls can contain nested elements, giving them nearly unlimited display abilities. They include the Label, Button, and ToolTip classes.  Headered content controls. These are content controls that allow you to add a main section of content and a separate title portion. They are usually intended to wrap larger blocks of user interface. They include the TabItem, GroupBox, and Expander classes.  Text controls. This is the small set of controls that allow users to enter input. The text controls support ordinary text (the TextBox), passwords (the PasswordBox).  List controls. These controls show collections of items in a list. They include the ListBox and ComboBox classes. Range-based controls. These controls have just one thing in common: a Value property that can be set to any number in a prescribed range. Examples include the Slider and ProgressBar classes.  Date controls. This category includes two controls that allow users to select dates: the Calendar and DatePicker.
  • 3. What you will learn in this chapter  ListView. The ListView derives from the plain-vanilla ListBox. It adds support for column-based display and the ability to switch quickly between different “views,” or display modes, without requiring you to rebind the data and rebuild the list.  TreeView. The TreeView is a hierarchical container, which means you can create a multilayered data display. For example, you could create a TreeView that shows category groups in its first level and shows the related products under each category node.  DataGrid. The DataGrid is WPF’s most full-featured data display tool. It divides your data into a grid of columns and rows, like the ListView, but has additional formatting features (such as the ability to freeze columns and style individual rows), and it supports in-place data editing.
  • 4. What you will learn in this chapter  Menus. They’re one of the oldest user interface controls, and they’ve changed surprisingly little in the past two decades. WPF includes solid, straightforward support for main menus and popup context menus.  Toolbars and status bars. They decorate the top and bottom of countless applications—sometimes when they aren’t even needed. WPF supports both controls with its customary flexibility, allowing you to insert virtually any control inside. However, the WPF toolbars and status bars don’t have many frills. They support overflow menus, but they don’t provide floating and docking capability.  Ribbons. With only a little more effort, you can add an Office-style ribbon to the top of your application window. It requires a separate (free) download, but you’ll get some valuable built-in features, such as configurable resizing. You’ll also get an Office-style menu feature to match.
  • 5. The ListView is a specialized list class that’s designed for displaying different views of the same data. The ListView is particularly useful if you need to build a multicolumn view that displays several pieces of information about each data item. The ListView derives from the ListBox class and extends it with a single detail: the View property. The View property is yet another extensibility point for creating rich list displays. If you don’t set the View property, the ListView behaves just like its lesser- powered ancestor, the ListBox. View property points to an instance of any class that derives from ViewBase (which is an abstract class). The ViewBase class is surprisingly simple; in fact, it’s little more than a package that binds together two styles. One style applies to the ListView control (and is referenced by the DefaultStyleKey property), and the other style applies to the items in the ListView (and is referenced by theZItemContainerDefaultStyleKey property). The DefaultStyleKey and ItemContainerDefaultStyleKey properties don’t actually provide the style; instead, they return a ResourceKey object that points to it. THE LISTVIEW
  • 6. View property is a useful abstraction of its advantages:  Reusable views. The ListView separates all the view-specific details into one object. That makes it easier to create views that are data-independent and can be used on more than one list.  Multiple views. The separation between the ListView control and the View objects also makes it easier to switch between multiple views with the same list. (For example, you use this technique in Windows Explorer to get a different perspective on your files and folders.) You could build the same feature by dynamically changing templates and styles, but it’s easier to have just one object that encapsulates all the view details.  Better organization. The view object wraps two styles: one for the root ListView control and one that applies to the individual items in the list. Because these styles are packaged together, it’s clear that these two pieces are related and may share certain details and interdependencies. For example, this makes a lot of sense for a column-based ListView, because it needs to keep its column headers and column data lined up. THE LISTVIEW
  • 7. Creating Columns with the GridView The GridView is a class that derives from ViewBase and represents a list view with multiple columns. It define those columns by adding GridViewColumn objects to the GridView.Columns collection. Figure 22-1 shows a straightforward example with three columns of information about a product. THE LISTVIEW
  • 8. Creating Columns with the GridView THE LISTVIEW
  • 9. Resizing Columns For more micromanaged control over column size, you can set a specific width when you declare the column: THE LISTVIEW
  • 10. Cell Templates The GridViewColumn.DisplayMemberBinding property isn’t the only option for showing data in a cell. Your other choice is the CellTemplate property, which takes a data template. This is exactly like the data templates you learned, except it applies to just one column. If you’re ambitious, you can give each column its own data template. Cell templates are a key piece of the puzzle when customizing the GridView. One feature that they allow is text wrapping. Ordinarily, the text in a column is wrapped in a single-line TextBlock. However, it’s easy to change this detail using a data template of your own devising: THE LISTVIEW
  • 12. Creating Custom View If the GridView doesn’t meet your needs, you can create your own view to extend the ListView’s capabilities. Unfortunately, it’s far from straightforward. To understand the problem, you need to know a little more about the way a view works. Views do their work by overriding two protected properties: DefaultStyleKey and ItemContainerDefaultKeyStyle. Each property returns a specialized object called a ResourceKey, which points to a style that you’ve defined in XAML. The DefaultStyleKey property points to the style that should be applied to configure the overall ListView. The temContainer.DefaultKeyStyle property points to the style that should be used to configure each ListViewItem in the ListView. Although these styles are free to tweak any property, they usually do their work by replacing the ControlTemplate that’s used for the ListView and the DataTemplate that’s used for each ListViewItem. THE LISTVIEW
  • 13. Creating Custom View The following example shows you how to create a grid that can be switched seamlessly from one view to another. The grid begins in the familiar column- separated view but also supports two tiled image views, as shown in Figure 22-3 and Figure 22-4. THE LISTVIEW
  • 14. Using the Listview C# Code XAML Code THE LISTVIEW <ListView x:Name="lstView" HorizontalAlignment="Left" Height="153" VerticalAlignment="Top" Width="465"> <ListView.View> <GridView> <GridView.ColumnHeaderContextMenu> <ContextMenu/> </GridView.ColumnHeaderContextMenu> <GridViewColumn Header="Firstname" Width="150" DisplayMemberBinding="{Binding Path=fName}"/> <GridViewColumn Header="Middlename" Width="150" DisplayMemberBinding="{Binding Path=mName}"/> <GridViewColumn Header="Lastname" Width="150" DisplayMemberBinding="{Binding Path=lName}"/> <GridViewColumn Header="Extension" Width="50" DisplayMemberBinding="{Binding Path=eName}"/> </GridView> </ListView.View> private void button_Click(object sender, RoutedEventArgs e) { List<Person> items = new List<Person>(); items.Add(new Person() { fName = firstnameTextBox .Text , mName = middlenameTextBox .Text , lName = lastnameTextBox .Text , eName = extensionnameTextBox.Text }); lstView.Items.Add(items); } public class Person { public string fName { get; set; } public string mName { get; set; } public string lName { get; set; } public string eName { get; set; } }
  • 16. The TreeView is a Windows staple, and it’s a common ingredient in everything from the Windows Explorer file browser to the .NET help library. WPF’s implementation of the TreeView is impressive, because it has full support for data binding. The TreeView is, at its heart, a specialized ItemsControl that hosts TreeViewItem objects. But unlike the ListViewItem, the TreeViewItem is not a content control. Instead, each TreeViewItem is a separate ItemsControl, with the ability to hold more TreeViewItem objects. This flexibility allows you to create a deeply layered data display. THE TREEVIEW
  • 17. Here’s the skeleton of a very basic TreeView, which is declared entirely in XAML markup: THE TREEVIEW
  • 18. Here’s the skeleton of a very basic TreeView, which is declared entirely in properties: THE TREEVIEW
  • 19. Binding a DataSet to a TreeView You can also use a TreeView to show a multilayered DataSet—one that has relationships linking one DataTable to another. For example, here’s a code routine that creates a DataSet, fills it with a table of products and a separate table of categories, and links the two tables together with a DataRelation object: THE TREEVIEW
  • 20. DataGrid is a data-display control that takes the information from a collection of objects and renders it in a grid of rows and cells. Each row corresponds to a separate object, and each column corresponds to a property in that object. The DataGrid adds much-needed versatility for dealing with data in WPF. Its column-based model gives it remarkable formatting flexibility. Its selection model allows you to choose whether users can select a row, multiple rows, or some combination of cells. Its editing support is powerful enough that you can use the DataGrid as an all-in-one data editor for simple and complex data. THE DATAGRID
  • 21. To create a quick-and-dirty DataGrid, you can use automatic column generation. To do so, you need to set the AutoGenerateColumns property to true (which is the default value): THE DATAGRID <DataGrid x:Name="gridPerson" AutoGenerateColumns="True"> </DataGrid>
  • 22. To create a quick-and-dirty DataGrid, you can use automatic column generation. To do so, you need to set the AutoGenerateColumns property to true (which is the default value): XAML Code C# Code THE DATAGRID private void Window Loaded(object sender, RoutedEventArgs e) { PersonalInformationDataSetTableAdapters.Person_tabTableAdapter pA; pA = new PersonalInformationDataSetTableAdapters.Person_tabTableAdapter(); PersonalInformationDataSet.Person_tabDataTable pT; pT = new PersonalInformationDataSet.Person_tabDataTable(); pA.Fill(pT); dtgPersonInfo.DataContext = pT; } DataGrid Name=“dtgPersonInfo" AutoGenerateColumns="True" ItemsSource="{Binding}" Grid.ColumnSpan="4" Margin="0,45,0,-205" Grid.Row="2"/>
  • 23. WPF provides two menu controls: Menu (for main menus) and ContextMenu (for popup menus that are attached to other elements). Like all the WPF classes, WPF performs the rendering for the Menu and ContextMenu controls. That means these controls aren’t simple Win32 wrappers, and they have the flexibility to be used in some unusual ways. MENUS
  • 24. The Menu Class WPF doesn’t make any assumption about where a stand-alone menu should be placed. Ordinarily, you’ll dock it at the top of your window using a DockPanel or the top row of a Grid, and you’ll stretch it across the entire width of your window. However, you can place a menu anywhere, even alongside other controls (as shown in Figure 25-1). Furthermore, you can add as many menus in a window as you want. Although it might not make much sense, you have the ability to stack menu bars or scatter them throughout your user MENUS
  • 25. Menu Items Menus are composed of MenuItem objects and Separator objects. The MenuItem class derives from HeaderedItemsControl, because each menu item has a header (which contains the text for that item) and can hold a collection of MenuItem objects (which represents a submenu). The Separator simply displays a horizontal line separating menu items. Here’s a straightforward combination of MenuItem objects that creates the rudimentary menu structure shown in Figure 25-3: MENUS Setting menu item in XAML
  • 26. Menu Items MENUS Setting menu item in Properties
  • 27. Toolbars and status bars are two well-worn staples of the Windows world. Both are specialized containers that hold a collection of items. Traditionally, a toolbar holds buttons, and a status bar consists primarily of text and other noninteractive indicators (like a progress bar). However, both toolbars and status bars are used with a variety of different controls. In Windows Forms, toolbars and status bars have their own content model. Although it’s still possible to place arbitrary controls inside a toolbar and status bar using a wrapper, the process isn’t seamless. The WPF toolbar and status bar don’t have this limitation. They support the WPF content model, allowing you to add any element to a toolbar or status bar and giving you unparalleled flexibility. TOOLBARS AND STATUS BARS
  • 28. The Toolbar A typical WPF ToolBar is filled with Button, ComboBox, CheckBox, RadioButton, and Separator objects. Because these elements are all content controls (except for the Separator), you can place text and image content inside. Although you can use other elements, such as Label and Image to put noninteractive elements into the ToolBar, the effect is often confusing. To demonstrate what this looks like, consider the simple markup shown here: TOOLBARS AND STATUS BARS Figure 25-5 shows this toolbar in action, with two CheckBox controls in the checked state and the drop-down list on display.
  • 29. The Toolbar To demonstrate in Designer shown here: TOOLBARS AND STATUS BARS
  • 30. The ToolbarTray The ToolBarTray makes it easier for toolbars to share the same row, or band. You can configure the ToolBarTray so that toolbars share a band, while others are placed on other bands. The ToolBarTray provides the shaded background behind the entire ToolBar area. But most important, the ToolBarTray adds support for toolbar drag-and-drop functionality. Unless you set the ToolBarTray.IsLocked property to true, the user can rearrange your toolbars in a ToolBar tray by clicking the grip at the left side. Toolbars can be repositioned in the same band or moved to a different band. TOOLBARS AND STATUS BARS
  • 31. The ToolbarTray Here’s some sample markup that creates several toolbars in a ToolBarTray. Figure 25-7 shows the result TOOLBARS AND STATUS BARS
  • 32. The ToolbarTray Here’s some sample designer that creates several toolbars in a ToolBarTray. Figure 25-7 shows the result TOOLBARS AND STATUS BARS
  • 33. The Statusbar The StatusBar doesn’t work very well if you want to use one of the ButtonBase-derived elements or the ComboBox. It doesn’t override the styles of any of these controls, so they look out of place in the status bar. If you need to create a status bar that includes these controls, you might consider docking an ordinary ToolBar control to the bottom of your window. It’s probably as a result of this general lack of features that the StatusBar is found in the System.Windows.Controls.Primitives namespace rather than in the more mainstream System.Windows.Controls namespace where the ToolBar control exists. TOOLBARS AND STATUS BARS
  • 34. The Statusbar One way to get proportionally or right-aligned items is to use a Grid for your layout container. The only trick is that you must wrap the child element in a StatusBarItem object in order to set the Grid.Column property appropriately. Here’s an example that uses a Grid to place one TextBlock on the left side of a StatusBar and another on the right side: TOOLBARS AND STATUS BARS
  • 35. The Statusbar Setting in designer. TOOLBARS AND STATUS BARS
  • 36. With the ribbon, Microsoft found itself faced with a familiar dilemma. To improve the productivity and consistency of all Windows applications, Microsoft wanted to encourage every application to adopt the ribbon. But because Microsoft also wanted to keep its competitive edge, it wasn’t in a rush to release the APIs that would make that possible. After all, Microsoft spent thousands of hours of research and development in perfecting its version of the ribbon, so it’s no surprise that the company took a few years to enjoy the result. Fortunately, the wait has ended, and Microsoft has now made a version of the ribbon available to WPF developers. The good news is that it’s completely free and respectably full-featured, including rich tooltips, drop-down buttons, dialog launchers, a quick access toolbar, and configurable resizing. RIBBONS
  • 37. The ribbon control isn’t included with the .NET Framework. Instead, it’s available as a separate download, which is considered to be a “preview” version at the time of this writing. You can download it from the Office UI Licensing website at http://msdn.microsoft.com/officeui (look for a “License the Office UI” link). Don’t be intimidated about the terminology—licensing simply means providing your contact information and accepting a one-page agreement that states that you will follow the Office UI design guidelines. (In other words, Microsoft doesn’t want you using the ribbon control if you aren’t using it right.) You can find ribbon guidelines and best practices at http://tinyurl.com/4dsbef. Once you’ve downloaded the ribbon, you’ll get a single compiled class library assembly, named RibbonControlsLibrary.dll. To start using the ribbon, add a reference to this library in any WPF application, and keep reading. RIBBONS
  • 38. Adding the Ribbon As with any control that’s not a part of the core WPF libraries, you need to map the control assembly to an XML prefix before you can use it: <Window x:Class="RibbonTest.MainWindow" ... xmlns:r= "clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"> You can then add an instance of the Ribbon control anywhere in your window: <r:Ribbon> </r:Ribbon> RIBBONS
  • 39. Adding the Ribbon The RibbonControlsLibrary.dll assembly addresses this issue by including the RibbonWindow—a class that derives from Window and integrates more seamlessly with the ribbon. Figure 25-8 compares the difference. RIBBONS
  • 40. Adding the Ribbon Here’s a basic skeleton for a custom window that derives from RibbonWindow and places the ribbon at the top, while reserving the second row of a Grid for the actual window content. RIBBONS
  • 41. Syling the Ribbon There’s one more detail to consider before you start filling the ribbon with buttons. Ordinarily, the ribbon is styled to look like the ribbon in Windows 7 applications (like Paint). That means the application menu button is a square that sits just under the window border and quick access toolbar, and the background of the ribbon blends into the background of the window frame. Your other choice is to use Office 2007 styling, which applies a more dramatic background color, turns the application menu button into a large circle, and moves it up to the top-left corner of the window. Figure 25-9 shows the difference. RIBBONS
  • 42. Commands The ribbon is built around the concept of commands. These commands power all parts of the ribbon, including its buttons, the application menu, and the quick access toolbar. Unlike WPF’s standard menu and toolbars, the ribbon doesn’t allow you to intercept Click events from its constituent controls. Instead, it forces you to use a higher-level design and to wire the ribbon controls to custom command objects. To support this system, the ribbon includes a new class that derives from RoutedCommand, called RibbonCommand. The advantage of this design is that it allows the ribbon to supply richer command functionality. (As you learned in Chapter 9, WPF’s basic command model is pretty modest.) The disadvantage of this design is that it means you can’t use any custom classes you may have already derived from RoutedCommand with the ribbon. RIBBONS
  • 43. Commands Table 25-1 lists the properties that the RibbonCommand adds to the base RoutedCommand. RIBBONS
  • 44. The Applpication Menu The easiest way to get started with the ribbon is to fill the application menu. The application menu is based on two straightforward classes: RibbonApplicationMenu (which derives from MenuBase) and RibbonMenuItem (which derives from MenuItem). This establishes a pattern you’ll see throughout this section—the ribbon takes the base WPF control class and derives more specialized versions. From a purist point of view, this isn’t ideal. The ToolBar and StatusBar have a far cleaner model, because they’re able to work with standard WPF controls, which they simply restyle. RIBBONS
  • 45. The Applpication Menu To create a menu, you create a new RibbonApplicationMenu object and use that to set the Ribbon.ApplicationMenu property. As you probably already expect, the RibbonApplicationMenu includes a collection of RibbonApplicationMenuItem objects, each of which represents a separate clickable menu item. Here’s a basic example outline that creates an application menu with three menu items: RIBBONS
  • 46. The Applpication Menu To configure each command, you simply need to supply a RibbonCommand object. This object specifies the menu text (through the LabelTitle property), an optional tooltip (using the ToolTipTitle, ToolTipDescription, and so on), an optional image (LargeImageSource), and the event handler that should be triggered when the menu item is clicked (Executed). As you learned in Chapter 9, you can also handle the CanExecute event to configure whether a command should be enabled or disabled. Here’s an example that fills in the three commands (but leaves out the optional tooltip properties): RIBBONS
  • 47. The Applpication Menu The top-level RibbonApplicationMenu object also needs a RibbonCommand object, even though it isn’t used to trigger a command! That’s because a few of the other properties, such as the tooltip properties and the image properties (which set the image that appears in the application menu button). If you’re using the default Windows 7 style, you need to set the SmallImage property, while the Office 2007 styles have a large application button and need to have the LargeImageSource property. It’s also worth noting that any RibbonApplicationMenuItem can hold more RibbonApplicationMenuItem objects to create a submenu. The submenu is displayed in the second column of the menu, as shown in Figure 25-10. RIBBONS
  • 48. The Applpication Menu When creating a submenu, you can set the RibbonCommand.LabelTitle property of the containing RibbonApplicationMenuItem object to add a title that will be shown over the submenu, as in Figure 25- 10. Here’s the markup you need: RIBBONS
  • 49. Tabs, Groups and Buttons The ribbon uses the same model to fill its toolbar tabs as it does to fill its application menu, just with a few extra layers. First, the ribbon holds a collection of tabs. In turn, each tab holds one or more groups, which is an outlined, titled, boxlike section of the ribbon. Lastly, each group holds one or more ribbon controls. Figure 25-11 shows this arrangement. RIBBONS
  • 50. Ribbon Sizing One of the ribbon’s most remarkable features is its ability to resize itself to fit the width of the window by reducing and rearranging the buttons in each groups. Figure 25-12 illustrates this process with a ribbon that has three copies of the File group. The first is fully expanded, the second is partially collapsed, and the second is completely collapsed. (It’s worth noting that in order to create this example, the ribbon must be explicitly configured to not collapse the first group. Otherwise, it will always try to partially collapse every group before it fully collapses any group.) RIBBONS
  • 51. Ribbon Sizing To take control of group resizing, you need to define multiple RibbonGroupSizeDefinition objects and order them from largest to smallest in a RibbonGroupSizeDefinitionCollection. As the group is collapsed, the ribbon can then switch from one layout to the next to reclaim more space, while keeping the layout you want (and ensuring that the controls you think are most important remain visible). Usually, you’ll place the RibbonGroupSizeDefinitionCollection in the Ribbon.Resources section, so you can reuse the same sequences of templates for more RIBBONS
  • 52. The Quick Access Toolbar The final ingredient that you’ll consider in the ribbon is the quick access toolbar (or QAT). It’s a narrow strip of commonly used buttons that sits either just above or just below the rest of the ribbon, depending on user selection. The QAT is represented by the QuickAccessToolBar object, which holds a series of RibbonButton objects. When defining the RibbonCommand for these objects, you need only supply the tooltip text and small image, because text labels and large images are never shown. RIBBONS
  • 53. The Quick Access Toolbar The only new detail in the QAT is the customize menu that appears when you click the drop-down arrow off the far right of it (Figure 25-13). You can use this menu to let users customize the commands that appear in the QAT. Or, you can disable the customize menu by setting QuickAccessToolBar.CanUserCustomize to false. RIBBONS