Skip to content

Commit 8e9afae

Browse files
Tris Shoresadegeo
andauthored
Content update - How to add an event handler using code (user story 1878475) (#1287)
* Add article, redirects, toc * Add alternative event handler assignments (commented) * Update dotnet-desktop-guide/net/wpf/events/how-to-add-an-event-handler-using-code.md Co-authored-by: Andy (Steve) De George <[email protected]> * Update dotnet-desktop-guide/net/wpf/events/how-to-add-an-event-handler-using-code.md Co-authored-by: Andy (Steve) De George <[email protected]> * Further edits Co-authored-by: Andy (Steve) De George <[email protected]>
1 parent a5e3c44 commit 8e9afae

File tree

18 files changed

+540
-0
lines changed

18 files changed

+540
-0
lines changed

.openpublishing.redirection.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,14 @@
604604
{
605605
"source_path": "dotnet-desktop-guide/framework/wpf/properties/xaml-loading-and-dependency-properties.md",
606606
"redirect_url": "/dotnet/desktop/wpf/advanced/xaml-loading-and-dependency-properties?view=netframeworkdesktop-4.8"
607+
},
608+
{
609+
"source_path": "dotnet-desktop-guide/net/wpf/advanced/how-to-add-an-event-handler-using-code.md",
610+
"redirect_url": "/dotnet/desktop/wpf/events/how-to-add-an-event-handler-using-code?view=netdesktop-6.0"
611+
},
612+
{
613+
"source_path": "dotnet-desktop-guide/framework/wpf/events/how-to-add-an-event-handler-using-code.md",
614+
"redirect_url": "/dotnet/desktop/wpf/advanced/how-to-add-an-event-handler-using-code?view=netframeworkdesktop-4.8"
607615
}
608616
]
609617
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
---
2+
title: "How to add an event handler using code"
3+
description: Learn how to add an event handler in code-behind for an element in Windows Presentation Foundation (WPF).
4+
ms.date: "02/01/2021"
5+
dev_langs:
6+
- "csharp"
7+
- "vb"
8+
helpviewer_keywords:
9+
- "event handlers [WPF], adding"
10+
- "XAML [WPF], adding event handlers"
11+
---
12+
<!-- The acrolinx score was 99 on 02/01/2021-->
13+
14+
# How to add an event handler using code (WPF .NET)
15+
16+
You can assign an event handler to an element in Windows Presentation Foundation (WPF) using markup or code-behind. Although it's customary to assign an event handler in Extensible Application Markup Language (XAML), sometimes you might have to assign an event handler in code-behind. For instance, use code when:
17+
18+
- You assign an event handler to an element after the markup page that contains the element loads.
19+
- You add an element and assign its event handler after the markup page that will contain the element loads.
20+
- You define the element tree for your application entirely in code.
21+
22+
[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)]
23+
24+
## Syntax for event handler assignment
25+
26+
C# supports event handler assignment using:
27+
28+
- The `+=` operator, which is also used in the common language runtime (CLR) event handling model.
29+
- The <xref:System.Windows.UIElement.AddHandler%2A?displayProperty=nameWithType> method.
30+
31+
VB supports event handler assignment using:
32+
33+
- The [AddHandler](/dotnet/visual-basic/language-reference/statements/addhandler-statement) statement with the [AddressOf](/dotnet/visual-basic/language-reference/operators/addressof-operator) operator, which is also used in the CLR event handling model.
34+
- The [Handles](/dotnet/visual-basic/language-reference/statements/handles-clause) keyword in the event handler definition. For more information, see [Visual Basic and WPF event handling](/dotnet/desktop/wpf/advanced/visual-basic-and-wpf-event-handling?view=netframeworkdesktop-4.8&preserve-view=true).
35+
- The <xref:System.Windows.UIElement.AddHandler%2A?displayProperty=nameWithType> method, together with the `AddressOf` operator to reference the event handler.
36+
37+
## Example
38+
39+
The following example uses XAML to define a <xref:System.Windows.Controls.Button> named `ButtonCreatedByXaml` and to assign the `ButtonCreatedByXaml_Click` method as its <xref:System.Windows.Controls.Primitives.ButtonBase.Click> event handler. `Click` is a built-in routed event for buttons that derive from <xref:System.Windows.Controls.Primitives.ButtonBase>.
40+
41+
:::code language="xaml" source="./snippets/how-to-add-an-event-handler-using-code/csharp/MainWindow.xaml" id="ButtonCreatedByXaml":::
42+
43+
The example uses code-behind to implement the `ButtonCreatedByXaml_Click` and `ButtonCreatedByCode_Click` handlers, and to assign the `ButtonCreatedByCode_Click` handler to the `ButtonCreatedByCode` and `StackPanel1` elements. Event handler methods can only be implemented in code-behind.
44+
45+
:::code language="csharp" source="./snippets/how-to-add-an-event-handler-using-code/csharp/MainWindow.xaml.cs" id="ButtonEventHandlers":::
46+
:::code language="vb" source="./snippets/how-to-add-an-event-handler-using-code/vb/MainWindow.xaml.vb" id="ButtonEventHandlers":::
47+
48+
When `ButtonCreatedByXaml` is clicked and its event handler runs, `ButtonCreatedByXaml_Click` programmatically:
49+
50+
1. Adds a new button named `ButtonCreatedByCode` to the already constructed XAML element tree.
51+
1. Specifies properties for the new button, such as the name, content, and background color.
52+
1. Assigns the `ButtonCreatedByCode_Click` event handler to `ButtonCreatedByCode`.
53+
1. Assigns the same `ButtonCreatedByCode_Click` event handler to `StackPanel1`.
54+
55+
When `ButtonCreatedByCode` is clicked:
56+
57+
1. The <xref:System.Windows.Controls.Primitives.ButtonBase.Click> routed event is raised on `ButtonCreatedByCode`.
58+
1. The `ButtonCreatedByCode_Click` event handler assigned to `ButtonCreatedByCode` is triggered.
59+
1. The `Click` routed event traverses up the element tree to `StackPanel1`.
60+
1. The `ButtonCreatedByCode_Click` event handler assigned to `StackPanel1` is triggered.
61+
1. The `Click` routed event continues up the element tree potentially triggering other `Click` event handlers assigned to other traversed elements.
62+
63+
The `ButtonCreatedByCode_Click` event handler obtains the following information about the event that triggered it:
64+
65+
- The [sender](xref:System.Windows.RoutedEventHandler) object, which is the element that the event handler is assigned to. The `sender` will be `ButtonCreatedByCode` the first time the handler runs, and `StackPanel1` the second time.
66+
- The <xref:System.Windows.RoutedEventArgs.Source?displayProperty=nameWithType> object, which is the element that originally raised the event. In this example, the `Source` is always `ButtonCreatedByCode`.
67+
68+
> [!NOTE]
69+
> A key difference between a routed event and a CLR event is that a routed event traverses the element tree, whereas a CLR event occurs only on the `sender`. As a result, a routed event `sender` can be any traversed element in the element tree.
70+
71+
For more information on how to create and handle routed events, see [How to create a custom routed event](/dotnet/desktop/wpf/advanced/how-to-create-a-custom-routed-event?view=netframeworkdesktop-4.8&preserve-view=true) and [Handle a routed event](/dotnet/desktop/wpf/advanced/how-to-handle-a-routed-event?view=netframeworkdesktop-4.8&preserve-view=true).
72+
73+
## See also
74+
75+
- [Routed events overview](/dotnet/desktop/wpf/advanced/routed-events-overview?view=netframeworkdesktop-4.8&preserve-view=true)
76+
- [XAML in WPF](/dotnet/desktop/wpf/advanced/xaml-in-wpf?view=netframeworkdesktop-4.8&preserve-view=true)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Configuration;
4+
using System.Data;
5+
using System.Linq;
6+
using System.Threading.Tasks;
7+
using System.Windows;
8+
9+
namespace CodeSampleCsharp
10+
{
11+
/// <summary>
12+
/// Interaction logic for App.xaml
13+
/// </summary>
14+
public partial class App : Application
15+
{
16+
}
17+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
using System.Windows;
2+
3+
[assembly: ThemeInfo(
4+
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
5+
//(used if a resource is not found in the page,
6+
// or application resource dictionaries)
7+
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
8+
//(used if a resource is not found in the page,
9+
// app, or any theme specific resource dictionaries)
10+
)]
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>WinExe</OutputType>
5+
<TargetFramework>net6.0-windows</TargetFramework>
6+
<UseWPF>true</UseWPF>
7+
<NeutralLanguage>en-us</NeutralLanguage>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<Compile Update="Properties\Resources.Designer.cs">
12+
<DesignTime>True</DesignTime>
13+
<AutoGen>True</AutoGen>
14+
<DependentUpon>Resources.resx</DependentUpon>
15+
</Compile>
16+
</ItemGroup>
17+
18+
<ItemGroup>
19+
<EmbeddedResource Update="Properties\Resources.resx">
20+
<Generator>ResXFileCodeGenerator</Generator>
21+
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
22+
</EmbeddedResource>
23+
</ItemGroup>
24+
25+
</Project>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<Window x:Class="CodeSampleCsharp.MainWindow"
2+
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3+
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4+
Title="How to add an event handler using code" Height="100" Width="300">
5+
6+
<!--<ButtonCreatedByXaml>-->
7+
<StackPanel Name="StackPanel1">
8+
<Button
9+
Name="ButtonCreatedByXaml"
10+
Click="ButtonCreatedByXaml_Click"
11+
Content="Create a new button with an event handler"
12+
Background="LightGray">
13+
</Button>
14+
</StackPanel>
15+
<!--</ButtonCreatedByXaml>-->
16+
</Window>
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Diagnostics;
4+
using System.Windows;
5+
using System.Windows.Controls;
6+
using System.Windows.Controls.Primitives;
7+
using System.Windows.Media;
8+
9+
namespace CodeSampleCsharp
10+
{
11+
/// <summary>
12+
/// Interaction logic for MainWindow.xaml.
13+
/// </summary>
14+
public partial class MainWindow : Window
15+
{
16+
public MainWindow()
17+
{
18+
InitializeComponent();
19+
}
20+
21+
//<ButtonEventHandlers>
22+
// The click event handler for the existing button 'ButtonCreatedByXaml'.
23+
private void ButtonCreatedByXaml_Click(object sender, RoutedEventArgs e)
24+
{
25+
// Create a new button.
26+
Button ButtonCreatedByCode = new();
27+
28+
// Specify button properties.
29+
ButtonCreatedByCode.Name = "ButtonCreatedByCode";
30+
ButtonCreatedByCode.Content = "New button and event handler created in code";
31+
ButtonCreatedByCode.Background = Brushes.Yellow;
32+
33+
// Add the new button to the StackPanel.
34+
StackPanel1.Children.Add(ButtonCreatedByCode);
35+
36+
// Assign an event handler to the new button using the '+=' operator.
37+
ButtonCreatedByCode.Click += new RoutedEventHandler(ButtonCreatedByCode_Click);
38+
39+
// Assign an event handler to the new button using the AddHandler method.
40+
// AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ButtonCreatedByCode_Click);
41+
42+
// Assign an event handler to the StackPanel using the AddHandler method.
43+
StackPanel1.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ButtonCreatedByCode_Click));
44+
}
45+
46+
// The Click event handler for the new button 'ButtonCreatedByCode'.
47+
private void ButtonCreatedByCode_Click(object sender, RoutedEventArgs e)
48+
{
49+
string sourceName = ((FrameworkElement)e.Source).Name;
50+
string senderName = ((FrameworkElement)sender).Name;
51+
52+
Debug.WriteLine($"Routed event handler attached to {senderName}, " +
53+
$"triggered by the Click routed event raised by {sourceName}.");
54+
}
55+
//</ButtonEventHandlers>
56+
57+
// Debug output when ButtonCreatedByCode is clicked:
58+
// Routed event handler attached to ButtonCreatedByCode, triggered by the Click routed event raised by ButtonCreatedByCode.
59+
// Routed event handler attached to StackPanel1, triggered by the Click routed event raised by ButtonCreatedByCode.
60+
}
61+
}

dotnet-desktop-guide/net/wpf/events/snippets/how-to-add-an-event-handler-using-code/csharp/Properties/Resources.Designer.cs

Lines changed: 63 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)