-
Notifications
You must be signed in to change notification settings - Fork 183
Content update - How to add an event handler using code (user story 1878475) #1287
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
20b7e3f
Add article, redirects, toc
880638c
Add alternative event handler assignments (commented)
e3e4102
Update dotnet-desktop-guide/net/wpf/events/how-to-add-an-event-handle…
afa6d96
Update dotnet-desktop-guide/net/wpf/events/how-to-add-an-event-handle…
08de7a1
Further edits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
76 changes: 76 additions & 0 deletions
76
dotnet-desktop-guide/net/wpf/events/how-to-add-an-event-handler-using-code.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| --- | ||
| title: "How to add an event handler using code" | ||
| description: Learn how to add an event handler in code-behind for an element in Windows Presentation Foundation (WPF). | ||
| ms.date: "02/01/2021" | ||
| dev_langs: | ||
| - "csharp" | ||
| - "vb" | ||
| helpviewer_keywords: | ||
| - "event handlers [WPF], adding" | ||
| - "XAML [WPF], adding event handlers" | ||
| --- | ||
| <!-- The acrolinx score was 99 on 02/01/2021--> | ||
|
|
||
| # How to add an event handler using code (WPF .NET) | ||
|
|
||
| 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: | ||
|
|
||
| - You assign an event handler to an element after the markup page that contains the element loads. | ||
| - You add an element and assign its event handler after the markup page that will contain the element loads. | ||
| - You define the element tree for your application entirely in code. | ||
|
|
||
| [!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)] | ||
|
|
||
| ## Syntax for event handler assignment | ||
|
|
||
| C# supports event handler assignment using: | ||
|
|
||
| - The `+=` operator, which is also used in the common language runtime (CLR) event handling model. | ||
| - The <xref:System.Windows.UIElement.AddHandler%2A?displayProperty=nameWithType> method. | ||
|
|
||
| VB supports event handler assignment using: | ||
|
|
||
| - 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. | ||
| - 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). | ||
| - The <xref:System.Windows.UIElement.AddHandler%2A?displayProperty=nameWithType> method, together with the `AddressOf` operator to reference the event handler. | ||
|
|
||
| ## Example | ||
|
|
||
| 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>. | ||
|
|
||
| :::code language="xaml" source="./snippets/how-to-add-an-event-handler-using-code/csharp/MainWindow.xaml" id="ButtonCreatedByXaml"::: | ||
|
|
||
| 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. | ||
|
|
||
| :::code language="csharp" source="./snippets/how-to-add-an-event-handler-using-code/csharp/MainWindow.xaml.cs" id="ButtonEventHandlers"::: | ||
| :::code language="vb" source="./snippets/how-to-add-an-event-handler-using-code/vb/MainWindow.xaml.vb" id="ButtonEventHandlers"::: | ||
|
|
||
| When `ButtonCreatedByXaml` is clicked and its event handler runs, `ButtonCreatedByXaml_Click` programmatically: | ||
|
|
||
| 1. Adds a new button named `ButtonCreatedByCode` to the already constructed XAML element tree. | ||
| 1. Specifies properties for the new button, such as the name, content, and background color. | ||
| 1. Assigns the `ButtonCreatedByCode_Click` event handler to `ButtonCreatedByCode`. | ||
| 1. Assigns the same `ButtonCreatedByCode_Click` event handler to `StackPanel1`. | ||
|
|
||
| When `ButtonCreatedByCode` is clicked: | ||
|
|
||
| 1. The <xref:System.Windows.Controls.Primitives.ButtonBase.Click> routed event is raised on `ButtonCreatedByCode`. | ||
| 1. The `ButtonCreatedByCode_Click` event handler assigned to `ButtonCreatedByCode` is triggered. | ||
| 1. The `Click` routed event traverses up the element tree to `StackPanel1`. | ||
| 1. The `ButtonCreatedByCode_Click` event handler assigned to `StackPanel1` is triggered. | ||
| 1. The `Click` routed event continues up the element tree potentially triggering other `Click` event handlers assigned to other traversed elements. | ||
|
|
||
| The `ButtonCreatedByCode_Click` event handler obtains the following information about the event that triggered it: | ||
|
|
||
| - 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. | ||
| - 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`. | ||
|
|
||
| > [!NOTE] | ||
| > 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. | ||
|
|
||
| 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). | ||
|
|
||
| ## See also | ||
|
|
||
| - [Routed events overview](/dotnet/desktop/wpf/advanced/routed-events-overview?view=netframeworkdesktop-4.8&preserve-view=true) | ||
| - [XAML in WPF](/dotnet/desktop/wpf/advanced/xaml-in-wpf?view=netframeworkdesktop-4.8&preserve-view=true) | ||
17 changes: 17 additions & 0 deletions
17
...p-guide/net/wpf/events/snippets/how-to-add-an-event-handler-using-code/csharp/App.xaml.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Configuration; | ||
| using System.Data; | ||
| using System.Linq; | ||
| using System.Threading.Tasks; | ||
| using System.Windows; | ||
|
|
||
| namespace CodeSampleCsharp | ||
| { | ||
| /// <summary> | ||
| /// Interaction logic for App.xaml | ||
| /// </summary> | ||
| public partial class App : Application | ||
| { | ||
| } | ||
| } |
10 changes: 10 additions & 0 deletions
10
...ide/net/wpf/events/snippets/how-to-add-an-event-handler-using-code/csharp/AssemblyInfo.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| using System.Windows; | ||
|
|
||
| [assembly: ThemeInfo( | ||
| ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located | ||
| //(used if a resource is not found in the page, | ||
| // or application resource dictionaries) | ||
| ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located | ||
| //(used if a resource is not found in the page, | ||
| // app, or any theme specific resource dictionaries) | ||
| )] |
25 changes: 25 additions & 0 deletions
25
...wpf/events/snippets/how-to-add-an-event-handler-using-code/csharp/CodeSampleCsharp.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>WinExe</OutputType> | ||
| <TargetFramework>net6.0-windows</TargetFramework> | ||
| <UseWPF>true</UseWPF> | ||
| <NeutralLanguage>en-us</NeutralLanguage> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Compile Update="Properties\Resources.Designer.cs"> | ||
| <DesignTime>True</DesignTime> | ||
| <AutoGen>True</AutoGen> | ||
| <DependentUpon>Resources.resx</DependentUpon> | ||
| </Compile> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <EmbeddedResource Update="Properties\Resources.resx"> | ||
| <Generator>ResXFileCodeGenerator</Generator> | ||
| <LastGenOutput>Resources.Designer.cs</LastGenOutput> | ||
| </EmbeddedResource> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
16 changes: 16 additions & 0 deletions
16
...ide/net/wpf/events/snippets/how-to-add-an-event-handler-using-code/csharp/MainWindow.xaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <Window x:Class="CodeSampleCsharp.MainWindow" | ||
| xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | ||
| xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | ||
| Title="How to add an event handler using code" Height="100" Width="300"> | ||
|
|
||
| <!--<ButtonCreatedByXaml>--> | ||
| <StackPanel Name="StackPanel1"> | ||
| <Button | ||
| Name="ButtonCreatedByXaml" | ||
| Click="ButtonCreatedByXaml_Click" | ||
| Content="Create a new button with an event handler" | ||
| Background="LightGray"> | ||
| </Button> | ||
| </StackPanel> | ||
| <!--</ButtonCreatedByXaml>--> | ||
| </Window> |
61 changes: 61 additions & 0 deletions
61
.../net/wpf/events/snippets/how-to-add-an-event-handler-using-code/csharp/MainWindow.xaml.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics; | ||
| using System.Windows; | ||
| using System.Windows.Controls; | ||
| using System.Windows.Controls.Primitives; | ||
| using System.Windows.Media; | ||
|
|
||
| namespace CodeSampleCsharp | ||
| { | ||
| /// <summary> | ||
| /// Interaction logic for MainWindow.xaml. | ||
| /// </summary> | ||
| public partial class MainWindow : Window | ||
| { | ||
| public MainWindow() | ||
| { | ||
| InitializeComponent(); | ||
| } | ||
|
|
||
| //<ButtonEventHandlers> | ||
| // The click event handler for the existing button 'ButtonCreatedByXaml'. | ||
| private void ButtonCreatedByXaml_Click(object sender, RoutedEventArgs e) | ||
| { | ||
| // Create a new button. | ||
| Button ButtonCreatedByCode = new(); | ||
|
|
||
| // Specify button properties. | ||
| ButtonCreatedByCode.Name = "ButtonCreatedByCode"; | ||
| ButtonCreatedByCode.Content = "New button and event handler created in code"; | ||
| ButtonCreatedByCode.Background = Brushes.Yellow; | ||
|
|
||
| // Add the new button to the StackPanel. | ||
| StackPanel1.Children.Add(ButtonCreatedByCode); | ||
|
|
||
| // Assign an event handler to the new button using the '+=' operator. | ||
| ButtonCreatedByCode.Click += new RoutedEventHandler(ButtonCreatedByCode_Click); | ||
|
|
||
| // Assign an event handler to the new button using the AddHandler method. | ||
| // AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ButtonCreatedByCode_Click); | ||
|
|
||
| // Assign an event handler to the StackPanel using the AddHandler method. | ||
| StackPanel1.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ButtonCreatedByCode_Click)); | ||
| } | ||
|
|
||
| // The Click event handler for the new button 'ButtonCreatedByCode'. | ||
| private void ButtonCreatedByCode_Click(object sender, RoutedEventArgs e) | ||
| { | ||
| string sourceName = ((FrameworkElement)e.Source).Name; | ||
| string senderName = ((FrameworkElement)sender).Name; | ||
|
|
||
| Debug.WriteLine($"Routed event handler attached to {senderName}, " + | ||
| $"triggered by the Click routed event raised by {sourceName}."); | ||
| } | ||
| //</ButtonEventHandlers> | ||
|
|
||
| // Debug output when ButtonCreatedByCode is clicked: | ||
| // Routed event handler attached to ButtonCreatedByCode, triggered by the Click routed event raised by ButtonCreatedByCode. | ||
| // Routed event handler attached to StackPanel1, triggered by the Click routed event raised by ButtonCreatedByCode. | ||
| } | ||
| } |
63 changes: 63 additions & 0 deletions
63
...s/snippets/how-to-add-an-event-handler-using-code/csharp/Properties/Resources.Designer.cs
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.