Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

464

Part IV Working with Windows Applications

Shortcut Menus

Many Windows-based applications make use of pop-up menus that appear when you rightclick a form or control. These menus are usually context-sensitive and display commands that

are applicable only to the control or form that currently has the focus. They are usually referred to as context or shortcut menus. You can easily add shortcut menus to a WPF application by using the ContextMenu class.

Creating Shortcut Menus

In the following exercises, you will create two shortcut menus. The first shortcut menu is attached to the firstName and lastName text box controls and allows the user to clear these

controls. The second shortcut menu is attached to the form and contains commands for saving the currently displayed member’s information and for clearing the form.

Note Text box controls are associated with a default shortcut menu that provides Cut, Copy, and Paste commands for performing text editing. The shortcut menu that you will define in the

following exercise will override this default menu.

Create the and shortcut menu

1.In the Design View window displaying Window1.xaml, add the following ContextMenu element shown in bold type to the end of the window resources in the XAML pane after the style definitions:

<Window.Resources>

...

<ContextMenu x:Key=”textBoxMenu” Style=”{StaticResource bellRingersFontStyle}”> </ContextMenu>

</Window.Resources>

This shortcut menu will be shared by the firstName and lastName text boxes. Adding the shortcut menu to the window resources makes it available to any controls in the window.

2.Add the following MenuItem element shown in bold type to the textBoxMenu shortcut menu:

<Window.Resources>

...

<ContextMenu x:Key=”textBoxMenu” Style=”{StaticResource bellRingersFontStyle}”>

<MenuItem Header=”Clear Name” Name=”clearName” />

</ContextMenu>

</Window.Resources>

Chapter 23 Working with Menus and Dialog Boxes

465

This code adds to the shortcut menu a menu item called clearName with the legend “Clear Name”.

3.In the XAML pane, modify the definitions of the firstName and lastName text box controls, and add the ContextMenu property, shown here in bold type:

<TextBox ... Name=”firstName” ContextMenu=”{StaticResource textBoxMenu}” ... />

...

<TextBox ... Name=”lastName” ContextMenu=”{StaticResource textBoxMenu}” ... />

The ContextMenu property determines which menu (if any) will be displayed when the user right-clicks the control.

4.Return to the definition of the textBoxMenu style, and to the clearText menu item add a Click event method called clearName_Click. (This is the default name generated by the

<New Event Handler> command.)

<MenuItem Header=”Clear Text” Name=”clearText” Click=”clearName_Click” />

5.In the Code and Text Editor window displaying Window1.xaml.cs, add the following statements to the clearName_Click event method that the <New Event Handler> command generated:

firstName.Text = String.Empty; lastName.Text = String.Empty;

This code clears both text boxes when the user clicks the Clear Name command on the shortcut menu.

6.On the Debug menu, click Start Without Debugging to build and run the application. When the form appears, click File, and then click New Member.

7.Type a name in the First Name and Last Name text boxes. Right-click the First Name text box. On the shortcut menu, click the Clear Name command, and verify that both text boxes are cleared.

8.Type a name in the First Name and Last Name text boxes. This time, right-click the Last Name text box. On the shortcut menu, click the Clear Name command and again verify that both text boxes are cleared.

9.Right-click anywhere on the form outside the First Name and Last Name text boxes.

Only the First Name and Last Name text boxes have shortcut menus, so no pop-up menu should appear.

10.Close the form, and return to Visual Studio 2008.

Now you can add the second shortcut menu, which contains commands that the user can use to save member information and to clear the fields on the form. To provide a bit of variation, and to show you how easy it is to create shortcut menus dynamically, in the following

466 Part IV Working with Windows Applications

exercise you will create the shortcut menu by using code. The best place to put this code is in the constructor of the form. You will then add code to enable the shortcut menu for the window when the user creates a new member.

Create the window shortcut menu

1.Switch to the Code and Text Editor window displaying the Window1.xaml.cs file.

2.Add the following private variable shown in bold type to the Window1 class:

public partial class Window1 : Window

{

...

private ContextMenu windowContextMenu = null;

...

}

3.Locate the constructor for the Window1 class. This is actually the first method in the class and is called Window1. Add the statements shown in bold type after the code that calls the Reset method to create the menu items for saving member details:

public Window1()

{

InitializeComponent();

this.Reset();

MenuItem saveMemberMenuItem = new MenuItem(); saveMemberMenuItem.Header = “Save Member Details”; saveMemberMenuItem.Click += new RoutedEventHandler(saveMember_Click);

}

This code sets the Header property for the menu item and then specifies that the Click event should invoke the saveMember_Click event method; this is the same method that you wrote in an earlier exercise in this chapter. The RoutedEventHandler type is a del-

egate that represents methods for handling the events raised by many WPF controls. (For more information about delegates and events, refer to Chapter 17, “Interrupting Program Flow and Handling Events.”)

4.In the Window1 constructor, add the following statements shown in bold type to create the menu items for clearing the fields on the form and resetting them to their default values:

public Window1()

{

...

MenuItem clearFormMenuItem = new MenuItem(); clearFormMenuItem.Header = “Clear Form”; clearFormMenuItem.Click += new RoutedEventHandler(clear_Click);

}

This menu item invokes the clear_Click event method when clicked by the user.

Chapter 23 Working with Menus and Dialog Boxes

467

5.In the Window1 constructor, add the following statements shown in bold type to construct the shortcut menu and populate it with the two menu items you have just created:

public Window1()

{

...

windowContextMenu = new ContextMenu(); windowContextMenu.Items.Add(saveMemberMenuItem); windowContextMenu.Items.Add(clearFormMenuItem);

}

The ContextMenu type contains a collection called Items that holds the menu items.

6.At the end of the newMember_Click event method, add the statement shown in bold type to associate the context menu with the form:

private void newMember_Click(object sender, RoutedEventArgs e)

{

...

this.ContextMenu = windowContextMenu;

}

Notice that the application associates the shortcut menu with the form only when the new member functionality is available. If you were to set the ContextMenu property of the form in the constructor, the Save Member Details and Clear Details shortcut menu

items would be available even when the controls on the form were disabled, which is not how you want this application to behave.

Tip You can disassociate a shortcut menu from a form by setting the ContextMenu property of the form to null.

7.On the Debug menu, click Start Without Debugging to build and run the application.

8.When the form appears, right-click the form and verify that the shortcut menu does not appear.

9.On the File menu, click New Member, and then input some details for a new member.

10.Right-click the form. On the shortcut menu, click Clear Form and verify that the fields on the form are reset to their default values.

11.Input some more member details. Right-click the form. On the shortcut menu, click Save Member Details. Verify that the “Member details saved” message box appears, and then click OK.

12.Close the form, and return to Visual Studio 2008.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]