- •Contents at a Glance
- •Table of Contents
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •Finding Your Best Starting Point in This Book
- •Conventions and Features in This Book
- •Conventions
- •Other Features
- •System Requirements
- •Code Samples
- •Installing the Code Samples
- •Using the Code Samples
- •Support for This Book
- •Questions and Comments
- •Beginning Programming with the Visual Studio 2008 Environment
- •Writing Your First Program
- •Using Namespaces
- •Creating a Graphical Application
- •Chapter 1 Quick Reference
- •Understanding Statements
- •Identifying Keywords
- •Using Variables
- •Naming Variables
- •Declaring Variables
- •Working with Primitive Data Types
- •Displaying Primitive Data Type Values
- •Using Arithmetic Operators
- •Operators and Types
- •Examining Arithmetic Operators
- •Controlling Precedence
- •Using Associativity to Evaluate Expressions
- •Associativity and the Assignment Operator
- •Incrementing and Decrementing Variables
- •Declaring Implicitly Typed Local Variables
- •Chapter 2 Quick Reference
- •Declaring Methods
- •Specifying the Method Declaration Syntax
- •Writing return Statements
- •Calling Methods
- •Specifying the Method Call Syntax
- •Applying Scope
- •Overloading Methods
- •Writing Methods
- •Chapter 3 Quick Reference
- •Declaring Boolean Variables
- •Using Boolean Operators
- •Understanding Equality and Relational Operators
- •Understanding Conditional Logical Operators
- •Summarizing Operator Precedence and Associativity
- •Using if Statements to Make Decisions
- •Understanding if Statement Syntax
- •Using Blocks to Group Statements
- •Cascading if Statements
- •Using switch Statements
- •Understanding switch Statement Syntax
- •Following the switch Statement Rules
- •Chapter 4 Quick Reference
- •Using Compound Assignment Operators
- •Writing while Statements
- •Writing for Statements
- •Understanding for Statement Scope
- •Writing do Statements
- •Chapter 5 Quick Reference
- •Coping with Errors
- •Trying Code and Catching Exceptions
- •Handling an Exception
- •Using Multiple catch Handlers
- •Catching Multiple Exceptions
- •Using Checked and Unchecked Integer Arithmetic
- •Writing Checked Statements
- •Writing Checked Expressions
- •Throwing Exceptions
- •Chapter 6 Quick Reference
- •The Purpose of Encapsulation
- •Controlling Accessibility
- •Working with Constructors
- •Overloading Constructors
- •Understanding static Methods and Data
- •Creating a Shared Field
- •Creating a static Field by Using the const Keyword
- •Chapter 7 Quick Reference
- •Copying Value Type Variables and Classes
- •Understanding Null Values and Nullable Types
- •Using Nullable Types
- •Understanding the Properties of Nullable Types
- •Using ref and out Parameters
- •Creating ref Parameters
- •Creating out Parameters
- •How Computer Memory Is Organized
- •Using the Stack and the Heap
- •The System.Object Class
- •Boxing
- •Unboxing
- •Casting Data Safely
- •The is Operator
- •The as Operator
- •Chapter 8 Quick Reference
- •Working with Enumerations
- •Declaring an Enumeration
- •Using an Enumeration
- •Choosing Enumeration Literal Values
- •Choosing an Enumeration’s Underlying Type
- •Working with Structures
- •Declaring a Structure
- •Understanding Structure and Class Differences
- •Declaring Structure Variables
- •Understanding Structure Initialization
- •Copying Structure Variables
- •Chapter 9 Quick Reference
- •What Is an Array?
- •Declaring Array Variables
- •Creating an Array Instance
- •Initializing Array Variables
- •Creating an Implicitly Typed Array
- •Accessing an Individual Array Element
- •Iterating Through an Array
- •Copying Arrays
- •What Are Collection Classes?
- •The ArrayList Collection Class
- •The Queue Collection Class
- •The Stack Collection Class
- •The Hashtable Collection Class
- •The SortedList Collection Class
- •Using Collection Initializers
- •Comparing Arrays and Collections
- •Using Collection Classes to Play Cards
- •Chapter 10 Quick Reference
- •Using Array Arguments
- •Declaring a params Array
- •Using params object[ ]
- •Using a params Array
- •Chapter 11 Quick Reference
- •What Is Inheritance?
- •Using Inheritance
- •Base Classes and Derived Classes
- •Calling Base Class Constructors
- •Assigning Classes
- •Declaring new Methods
- •Declaring Virtual Methods
- •Declaring override Methods
- •Understanding protected Access
- •Understanding Extension Methods
- •Chapter 12 Quick Reference
- •Understanding Interfaces
- •Interface Syntax
- •Interface Restrictions
- •Implementing an Interface
- •Referencing a Class Through Its Interface
- •Working with Multiple Interfaces
- •Abstract Classes
- •Abstract Methods
- •Sealed Classes
- •Sealed Methods
- •Implementing an Extensible Framework
- •Summarizing Keyword Combinations
- •Chapter 13 Quick Reference
- •The Life and Times of an Object
- •Writing Destructors
- •Why Use the Garbage Collector?
- •How Does the Garbage Collector Work?
- •Recommendations
- •Resource Management
- •Disposal Methods
- •Exception-Safe Disposal
- •The using Statement
- •Calling the Dispose Method from a Destructor
- •Making Code Exception-Safe
- •Chapter 14 Quick Reference
- •Implementing Encapsulation by Using Methods
- •What Are Properties?
- •Using Properties
- •Read-Only Properties
- •Write-Only Properties
- •Property Accessibility
- •Understanding the Property Restrictions
- •Declaring Interface Properties
- •Using Properties in a Windows Application
- •Generating Automatic Properties
- •Initializing Objects by Using Properties
- •Chapter 15 Quick Reference
- •What Is an Indexer?
- •An Example That Doesn’t Use Indexers
- •The Same Example Using Indexers
- •Understanding Indexer Accessors
- •Comparing Indexers and Arrays
- •Indexers in Interfaces
- •Using Indexers in a Windows Application
- •Chapter 16 Quick Reference
- •Declaring and Using Delegates
- •The Automated Factory Scenario
- •Implementing the Factory Without Using Delegates
- •Implementing the Factory by Using a Delegate
- •Using Delegates
- •Lambda Expressions and Delegates
- •Creating a Method Adapter
- •Using a Lambda Expression as an Adapter
- •The Form of Lambda Expressions
- •Declaring an Event
- •Subscribing to an Event
- •Unsubscribing from an Event
- •Raising an Event
- •Understanding WPF User Interface Events
- •Using Events
- •Chapter 17 Quick Reference
- •The Problem with objects
- •The Generics Solution
- •Generics vs. Generalized Classes
- •Generics and Constraints
- •Creating a Generic Class
- •The Theory of Binary Trees
- •Building a Binary Tree Class by Using Generics
- •Creating a Generic Method
- •Chapter 18 Quick Reference
- •Enumerating the Elements in a Collection
- •Manually Implementing an Enumerator
- •Implementing the IEnumerable Interface
- •Implementing an Enumerator by Using an Iterator
- •A Simple Iterator
- •Chapter 19 Quick Reference
- •What Is Language Integrated Query (LINQ)?
- •Using LINQ in a C# Application
- •Selecting Data
- •Filtering Data
- •Ordering, Grouping, and Aggregating Data
- •Joining Data
- •Using Query Operators
- •Querying Data in Tree<TItem> Objects
- •LINQ and Deferred Evaluation
- •Chapter 20 Quick Reference
- •Understanding Operators
- •Operator Constraints
- •Overloaded Operators
- •Creating Symmetric Operators
- •Understanding Compound Assignment
- •Declaring Increment and Decrement Operators
- •Implementing an Operator
- •Understanding Conversion Operators
- •Providing Built-In Conversions
- •Creating Symmetric Operators, Revisited
- •Adding an Implicit Conversion Operator
- •Chapter 21 Quick Reference
- •Creating a WPF Application
- •Creating a Windows Presentation Foundation Application
- •Adding Controls to the Form
- •Using WPF Controls
- •Changing Properties Dynamically
- •Handling Events in a WPF Form
- •Processing Events in Windows Forms
- •Chapter 22 Quick Reference
- •Menu Guidelines and Style
- •Menus and Menu Events
- •Creating a Menu
- •Handling Menu Events
- •Shortcut Menus
- •Creating Shortcut Menus
- •Windows Common Dialog Boxes
- •Using the SaveFileDialog Class
- •Chapter 23 Quick Reference
- •Validating Data
- •Strategies for Validating User Input
- •An Example—Customer Information Maintenance
- •Performing Validation by Using Data Binding
- •Changing the Point at Which Validation Occurs
- •Chapter 24 Quick Reference
- •Querying a Database by Using ADO.NET
- •The Northwind Database
- •Creating the Database
- •Using ADO.NET to Query Order Information
- •Querying a Database by Using DLINQ
- •Creating and Running a DLINQ Query
- •Deferred and Immediate Fetching
- •Joining Tables and Creating Relationships
- •Deferred and Immediate Fetching Revisited
- •Using DLINQ to Query Order Information
- •Chapter 25 Quick Reference
- •Using Data Binding with DLINQ
- •Using DLINQ to Modify Data
- •Updating Existing Data
- •Adding and Deleting Data
- •Chapter 26 Quick Reference
- •Understanding the Internet as an Infrastructure
- •Understanding Web Server Requests and Responses
- •Managing State
- •Understanding ASP.NET
- •Creating Web Applications with ASP.NET
- •Building an ASP.NET Application
- •Understanding Server Controls
- •Creating and Using a Theme
- •Chapter 27 Quick Reference
- •Comparing Server and Client Validations
- •Validating Data at the Web Server
- •Validating Data in the Web Browser
- •Implementing Client Validation
- •Chapter 28 Quick Reference
- •Managing Security
- •Understanding Forms-Based Security
- •Implementing Forms-Based Security
- •Querying and Displaying Data
- •Understanding the Web Forms GridView Control
- •Displaying Customer and Order History Information
- •Paging Data
- •Editing Data
- •Updating Rows Through a GridView Control
- •Navigating Between Forms
- •Chapter 29 Quick Reference
- •What Is a Web Service?
- •The Role of SOAP
- •What Is the Web Services Description Language?
- •Nonfunctional Requirements of Web Services
- •The Role of Windows Communication Foundation
- •Building a Web Service
- •Creating the ProductsService Web Service
- •Web Services, Clients, and Proxies
- •Talking SOAP: The Easy Way
- •Consuming the ProductsService Web Service
- •Chapter 30 Quick Reference
452 Part IV Working with Windows Applications
The order in which these commands appear tends to be the same across applications; for example, the Exit command is invariably the last command on the File menu. There might be other application-specific commands on the File menu as well.
An application often has an Edit menu containing commands such as Cut, Paste, Clear, and Find. There are usually some additional application-specific menus on the menu bar, but again, convention dictates that the final menu is the Help menu, which contains access to Help as well as “about” information, which contains copyright and licensing details for the application. In a well-designed application, most menus are predictable and help ensure that the application is easy to learn and use.
Tip Microsoft publishes a full set of guidelines for building intuitive user interfaces, including menu design, on the Microsoft Web site at http://msdn2.microsoft.com/en-us/library /Aa286531.aspx.
Menus and Menu Events
WPF provides the Menu control as a container for menu items. The Menu control provides a basic shell for defining a menu. Like most aspects of WPF, the Menu control is very flexible so that you can define a menu structure consisting of almost any type of WPF control. You are probably familiar with menus that contain text items that you can click to perform
a command. WPF menus can also contain buttons, text boxes, combo boxes, and so on. You can define menus by using the XAML pane in the Design View window, and you can also con-
struct menus at run time by using Microsoft Visual C# code. Laying out a menu is only half of the story. When a user clicks a command on a menu, the user expects something to happen! Your application acts on the commands by trapping menu events and executing code in much the same way as handling control events.
Creating a Menu
In the following exercise, you will use the XAML pane to create menus for the Middleshire Bell Ringers Association application. You will learn how to manipulate and create menus through code later in this chapter.
Create the application menu
1.Start Microsoft Visual Studio 2008 if it is not already running.
2.Open the BellRingers solution located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 23\BellRingers folder in your Documents folder. This is a copy of the application that you built in Chapter 22.
Chapter 23 Working with Menus and Dialog Boxes |
453 |
3.Display Window1.xaml in the Design View window. (Double-click Window1.xaml in
Solution Explorer.)
4.From the Toolbox, drag a DockPanel control from the Controls section anywhere onto the form. In the Properties window, set the Width property of the DockControl to Auto, set the HorizontalAlignment property to Stretch, set the VerticalAlignment property to
Top, and set the Margin property to 0.
Note Setting the Margin property to 0 is the same as setting it to 0, 0, 0, 0.
The DockControl control should appear at the top of the form, occupying the full width of the form. (It will cover the First Name, Last Name, Tower, and Captain user interface
elements.)
The DockPanel control is a panel control that you can use for controlling the arrangement of other controls that you place on it, like the Grid and StackPanel controls that
you met in Chapter 22. You can add a menu directly to a form, but it is better practice to place it on a DockPanel because you can then more easily manipulate the menu and
its positioning on the form. For example, if you want to place the menu at the bottom or on one side, you can relocate the entire menu elsewhere on the form simply by moving the panel either at design time or at run time by executing code.
5.From the Toolbox, drag a Menu control from the Controls section onto the DockPanel control. In the Properties window, set the DockPanel.Dock property to Top, set the Width property to Auto, set the HorizontalAlignment property to Stretch, and set the
VerticalAlignment property to Top.
The Menu control appears as a gray bar across the top of the DockPanel. If you examine the code for the DockPanel and Menu controls in the XAML pane, they should look like this:
<DockPanel Height=”100” HorizontalAlignment=”Stretch” Margin=”0” Name=”dockPanel1” VerticalAlignment=”Top” Width=”Auto”>
<Menu Height=”22” Name=”menu1” Width=”Auto” DockPanel.Dock=”Top” VerticalAlignment=”Top”>
</DockPanel>
The HorizontalAlignment property does not appear in the XAML code because the value “Stretch” is the default value for this property.
Note Throughout this chapter, lines from the XAML pane are shown split and indented so that they fit on the printed page.
454 |
Part IV Working with Windows Applications |
6.In the XAML pane, modify the definition of the Menu control and add the MenuItem elements as shown in bold type in the following code. Notice that MenuItem elements appear as children of the Menu control, so replace the closing tag delimiter (/>) of the Menu element with a regular tag delimiter (>), and place a separate closing </Menu> element at the end.
<Menu Height=”22” Name=”menu1” Width=”Auto” DockPanel.Dock=”Top” VerticalAlignment=”Top” HorizontalAlignment=”Stretch” >
<MenuItem Header=”_File” /> <MenuItem Header=”_Help” />
</Menu>
The Header attribute of the MenuItem element specifies the text that appears for the menu item. The underscore (_) in front of a letter provides fast access to that menu item when the user presses the Alt key and the letter following the underscore (in this case, Alt+F for File or Alt+H for Help). This is another common convention. At run time, when the user presses the Alt key, the F at the start of File appears underscored. Do not use the same access key more than once on any menu because you will confuse the user (and probably the application).
Note The Properties window for the Menu control displays a property called Items. If you
click this property and then click the ellipsis button that appears in this property, the Collection Editor appears. At the time of writing, the current release of Visual Studio 2008
(Beta 2) allows you to use this window to remove items from a menu, change the order of items on a menu, and set the properties of these items, but it does not allow you to add new items to a menu. Consequently, in this chapter you will use the XAML pane to define the structure of your menus.
7.On the Debug menu, click Start Without Debugging to build and run the application.
When the form appears, you should see the menu at the top of the window underneath the title bar. Press the Alt key; the menu should get the focus, and the “F” in “File” and the “H” in “Help” should both be underscored, like this:
If you click either menu item, nothing currently happens because you have not defined the child menus that each of these items will contain.
8.Close the form and return to Visual Studio 2008.
Chapter 23 Working with Menus and Dialog Boxes |
455 |
9.In the XAML pane, modify the definition of the _File menu item, and add the child menu items together with a closing </MenuItem> element as shown here in bold type:
<MenuItem Header=”_File” >
<MenuItem Header=”_New Member” Name=”newMember” /> <MenuItem Header=”_Save Member Details” Name=”saveMember” /> <Separator/>
<MenuItem Header=”E_xit” Name=”exit” /> </MenuItem>
This XAML code adds New Member, Save Member Details, and Exit as commands to the File menu. The <Separator/> element appears as a bar when the menu is displayed and is conventionally used to group related menu items.
10.Modify the definition of the _Help menu item, and add the child menu item as shown in bold type here:
<MenuItem Header=”_Help” >
<MenuItem Header=”_About Middleshire Bell Ringers” Name=”about” /> </MenuItem>
11.On the Debug menu, click Start Without Debugging to build and run the application.
When the form appears, click the File menu. You should see the child menu items, like this:
You can also click the Help menu to display the About Middleshire Bell Ringers child menu item.
12.Close the form, and return to Visual Studio 2008.
As a further touch, you can add icons to menu items. Many applications, including Visual Studio 2008, make use of icons in menus to provide an additional visual cue.
13.In Solution Explorer, right-click the BellRingers project, point to Add, and then click
Existing Item. In the Add Existing Item – BellRingers dialog box, move to the folder
Microsoft Press\Visual CSharp Step By Step\Chapter 23 under your Documents folder, in the File name box type “Ring.bmp” “Face.bmp” “Note.bmp” (including the quotation marks), and then click Add.
This action adds the three image files as resources to your application.
456 |
Part IV Working with Windows Applications |
14.In the XAML pane, modify the definitions of the newMember, saveMember, and about menu items and add MenuItem.Icon child elements that refer to each of the three icon files you added to the project in the preceding step, as shown in bold type here:
<Menu Height=”22” Name=”menu1” ... > <MenuItem Header=”_File” >
<MenuItem Header=”_New Member” Name=”newMember” >
<MenuItem.Icon>
<Image Source=”face.bmp”/> </MenuItem.Icon>
</MenuItem>
<MenuItem Header=”_Save Member Details” Name=”saveMember” >
<MenuItem.Icon>
<Image Source=”note.bmp”/> </MenuItem.Icon>
</MenuItem>
<Separator/>
<MenuItem Header=”E_xit” Name=”exit”/> </MenuItem>
<MenuItem Header=”_Help”>
<MenuItem Header=”_About Middleshire Bell Ringers” Name=”about” >
<MenuItem.Icon>
<Image Source=”ring.bmp”/> </MenuItem.Icon>
</MenuItem>
</MenuItem>
</Menu>
15.The final tweak is to ensure that the text for the menu items is styled in a consistent manner with the rest of the form. In the XAML pane, edit the definition of the top-level menu1 element and set the Style property to the BellRingersFontStyle style, as shown in bold type here:
<Menu Style=”{StaticResource bellRingersFontStyle}” ... Name=”menu1” ... >
Note that the child menu items automatically inherit the style from the top-level menu item that contains them.
16.On the Debug menu, click Start Without Debugging to build and run the application again.
When the form appears, click the File menu. You should now see that the text of
the menu items is displayed in the correct font and that the icons appear with the child menu items, like this:
17. Close the form, and return to Visual Studio 2008.
Chapter 23 Working with Menus and Dialog Boxes |
457 |
Types of Menu Items
You have been using the MenuItem element to add child menu items to a Menu control. You have seen that you can specify the items in the top-level menu as MenuItem elements and then add nested MenuItem elements to define your menu structure.
The nested MenuItem elements can themselves contain further nested MenuItem elements if you want to create cascading menus. In theory, you can continue this process to a very deep level, but in practice you should probably not go beyond two levels of nesting.
However, you are not restricted to using the MenuItem element. You can also add combo boxes, text boxes, and most other types of controls to WPF menus. For example, the following menu structure contains a button and a combo box:
<Menu ...>
<MenuItem Header=”Miscellaneous”> <Button>Add new member</Button> <ComboBox Text=”Towers”>
<ComboBox.Items>
<ComboBoxItem> Great Shevington
</ComboBoxItem>
<ComboBoxItem> Little Mudford
</ComboBoxItem>
<ComboBoxItem> Upper Gumtree
</ComboBoxItem>
<ComboBoxItem> Downley Hatch
</ComboBoxItem>
</ComboBox.Items>
</ComboBox>
</MenuItem>
</Menu>
At run time, the menu structure looks like this:
Although you have great freedom when designing your menus, you should endeavor to keep things simple and not be too elaborate. A menu such as this is not very intuitive!
