Files
docs-desktop/dotnet-desktop-guide/framework/wpf/advanced/how-to-add-an-event-handler-using-code.md
Andy (Steve) De George be103da07e Replace various WPF include files with content (#1335)
* net-current-v30plus-md.md

* net-current-v40plus-md.md

* tla2sharptla-ui-md.md

* tla2sharptla-uiautomation-md.md

* tla2sharptla-winclient-md.md

* tla2sharptla-xaml-md.md

* tlasharptla-ui-md.md

* tlasharptla-uiautomation-md.md

* tlasharptla-winclient-md.md

* tlasharptla-xaml-md.md

* fix warnings
2022-03-16 12:14:11 -04:00

2.9 KiB

title, description, ms.date, dev_langs, helpviewer_keywords, ms.assetid
title description ms.date dev_langs helpviewer_keywords ms.assetid
How to: Add an Event Handler Using Code Use this example to learn how to add an event handler to an element in Windows Presentation Foundation by using code, instead of declaring it by using XAML. 03/30/2017
csharp
vb
event handlers [WPF], adding
XAML [WPF], adding event handlers
269c61e0-6bd9-4291-9bed-1c5ee66da486

How to: Add an Event Handler Using Code

This example shows how to add an event handler to an element by using code.

If you want to add an event handler to a XAML element, and the markup page that contains the element has already been loaded, you must add the handler using code. Alternatively, if you are building up the element tree for an application entirely using code and not declaring any elements using XAML, you can call specific methods to add event handlers to the constructed element tree.

Example

The following example adds a new xref:System.Windows.Controls.Button to an existing page that is initially defined in XAML. A code-behind file implements an event handler method and then adds that method as a new event handler on the xref:System.Windows.Controls.Button.

The C# example uses the += operator to assign a handler to an event. This is the same operator that is used to assign a handler in the common language runtime (CLR) event handling model. Microsoft Visual Basic does not support this operator as a means of adding event handlers. It instead requires one of two techniques:

[!code-xamlRoutedEventAddRemoveHandler#XAML]

[!code-csharpRoutedEventAddRemoveHandler#Handler] [!code-vbRoutedEventAddRemoveHandler#Handler]

Note

Adding an event handler in the initially parsed XAML page is much simpler. Within the object element where you want to add the event handler, add an attribute that matches the name of the event that you want to handle. Then specify the value of that attribute as the name of the event handler method that you defined in the code-behind file of the XAML page. For more information, see XAML in WPF or Routed Events Overview.

See also