Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Учебник_ПОА.doc
Скачиваний:
93
Добавлен:
13.02.2015
Размер:
2.65 Mб
Скачать

How to: Create Event Handlers for wpf Controls

You can add the default event handler for many controls by double-clicking the control in Design view. You can also create an event handler for controls in a Windows Presentation Foundation (WPF) application by adding an attribute to the control's XAML representation. This XAML markup defines the event and the name of the method that will handle the event. Then, you write the code for the method in the Code Editor.

To create an event handler for a button

  1. Create a WPF application by using Visual C# Express Edition. For more information, see How to: Create a New WPF Application Project.

  2. Drag a Button from the Toolbox to the WPF window, and then select the button.

  3. Double-click the button.

The Click event handler is created and the cursor is positioned in the event handler in the Code Editor.

  1. Add the following code to the event handler:

    MessageBox.Show("Event handler was created by " + "double-clicking the button.");

  2. Drag a second Button control from the Toolbox to the WPF design surface, and then select the button.

  3. Add an attribute named Click to the Button element in the XAML editor, and set its value to ButtonOKClicked. This is the name that you will give the event handler in code. For example, the attribute can be written as follows: Click="ButtonOKClicked".

  4. Right-click the designer and then click View Code.

  5. Add the following event handler to the Window1 class. This code displays a message whenever you click the button.

    private void ButtonOKClicked(object sender, RoutedEventArgs e)

    {

    MessageBox.Show("Event handler was created manually.");

    }

  6. Press F5 to run the program.

  7. When the window appears, click a button.

  8. Verify that the correct text appears in a message box when you click each button, and then close the application.

Создание обработчиков событий для элементов управления wpf

Для многих элементов управления можно добавить заданные по умолчанию обработчики событий. Для этого в режиме конструктора следует дважды щелкнуть нужный элемент управления. Кроме того, обработчик событий для элементов управления можно создать в приложении Windows Presentation Foundation (WPF), добавив атрибут к представлению XAML элемента управления. Разметка XAML определяет событие и имя метода, который будет обрабатывать событие. Затем в редакторе кода можно написать код для метода.

Создание обработчика событий для кнопки

  1. Создайте приложение WPF, используя Visual C#, экспресс-выпуск.

  2. Перетащите элемент управления Button из панели элементов в окно WPF, а затем выберите кнопку.

  3. Дважды щелкните кнопку.

Будет создан обработчик событий Click, а указатель мыши будет находиться в обработчике событий в редакторе кода.

  1. Добавьте следующий код в обработчик событий.

    MessageBox.Show("Event handler was created by " + "double-clicking the button.");

  2. Перетащите второй элемент управления Button из панели элементов на поверхность проектирования WPF, а затем выберите эту кнопку.

  3. Добавьте атрибут с именем Click к элементу Button в редакторе XAML и присвойте ему значение ButtonOKClicked. Это имя, которое будет присвоено обработчику событий в коде. Например, атрибут может быть записан следующим образом: Click="ButtonOKClicked"

  4. Правой клавишей мыши щелкните конструктор и выберите команду Просмотреть код.

  5. Добавьте следующий обработчик событий в класс Window1. Этот код отображает сообщение при каждом нажатии кнопки.

    private void ButtonOKClicked(object sender, RoutedEventArgs e)

    {

    MessageBox.Show("Event handler was created manually.");

    }

  6. Нажмите клавишу F5 для выполнения программы.

  7. При появлении окна нажмите кнопку.

  8. Убедитесь, что в окне сообщения при нажатии каждой кнопки появляется правильный текст, а затем закройте приложение.