如何使用代码添加事件处理程序

可以在 Windows Presentation Foundation(WPF)中使用标记或代码后置将事件处理程序分配给元素。 虽然通常在可扩展应用程序标记语言(XAML)中分配事件处理程序,但有时您可能需要在后台代码中分配事件处理程序。 例如,在以下情况下使用代码:

  • 标记页加载包含该元素后,将事件处理程序分配给元素。
  • 在将包含元素的标记页加载后,添加元素并分配其事件处理程序。
  • 完全在代码中为应用程序定义元素树。

先决条件

本文假设您具有有关路由事件的基本知识,并且已经阅读了 路由事件概述。 若要遵循本文中的示例,如果你熟悉可扩展应用程序标记语言(XAML),并且知道如何编写 Windows Presentation Foundation (WPF) 应用程序,则它很有帮助。

事件处理程序分配的语法

C# 支持使用以下方法分配事件处理程序:

  • += 运算符也用于公共语言运行时 (CLR) 事件处理模型。
  • UIElement.AddHandler 方法。

VB 支持使用以下方法分配事件处理程序:

示例:

以下示例使用 XAML 定义 Button 命名 ButtonCreatedByXaml 方法并将其分配 ButtonCreatedByXaml_Click 为其 Click 事件处理程序。 Click 是派生自 ButtonBase的按钮的内置路由事件。

<StackPanel Name="StackPanel1">
    <Button
        Name="ButtonCreatedByXaml" 
        Click="ButtonCreatedByXaml_Click"
        Content="Create a new button with an event handler"
        Background="LightGray">
    </Button>
</StackPanel>

该示例使用后台代码来实现ButtonCreatedByXaml_ClickButtonCreatedByCode_Click处理程序,并将ButtonCreatedByCode_Click处理程序分配给ButtonCreatedByCodeStackPanel1元素。 事件处理程序方法只能在代码隐藏中实现。

// 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}.");
}
' The click event handler for the existing button 'ButtonCreatedByXaml'.
Private Sub ButtonCreatedByXaml_Click(sender As Object, e As RoutedEventArgs)

    ' Create a new button and specify button properties.
    Dim ButtonCreatedByCode As New Button With {
        .Name = "ButtonCreatedByCode",
        .Content = "New button and event handler created in code",
        .Background = Brushes.Yellow
    }

    ' Add the new button to the StackPanel.
    StackPanel1.Children.Add(ButtonCreatedByCode)

    ' Assign an event handler to the new button using the AddHandler statement.
    AddHandler ButtonCreatedByCode.Click, AddressOf ButtonCreatedByCode_Click

    ' Assign an event handler to the new button using the AddHandler method.
    ' ButtonCreatedByCode.AddHandler(ButtonBase.ClickEvent, New RoutedEventHandler(AddressOf ButtonCreatedByCode_Click))

    ' Assign an event handler to the StackPanel using the AddHandler method.
    StackPanel1.AddHandler(ButtonBase.ClickEvent, New RoutedEventHandler(AddressOf ButtonCreatedByCode_Click))

End Sub

' The Click event handler for the new button 'ButtonCreatedByCode'.
Private Sub ButtonCreatedByCode_Click(sender As Object, e As RoutedEventArgs)

    Dim sourceName As String = CType(e.Source, FrameworkElement).Name
    Dim senderName As String = CType(sender, FrameworkElement).Name

    Debug.WriteLine($"Routed event handler attached to {senderName}, " +
        $"triggered by the Click routed event raised by {sourceName}.")

End Sub

单击并运行其事件处理程序时 ButtonCreatedByXamlButtonCreatedByXaml_Click 以编程方式:

  1. 向已构造的 XAML 元素树添加新按钮 ButtonCreatedByCode
  2. 指定新按钮的属性,例如名称、内容和背景色。
  3. ButtonCreatedByCode_Click 事件处理程序 ButtonCreatedByCode分配给 。
  4. 将相同的 ButtonCreatedByCode_Click 事件处理程序分配给 StackPanel1

单击 ButtonCreatedByCode 时:

  1. 引发 Click 上的 ButtonCreatedByCode 路由事件。
  2. 分配给ButtonCreatedByCodeButtonCreatedByCode_Click事件处理程序已被触发。
  3. Click 路由事件在元素树中向上遍历到 StackPanel1
  4. 将触发分配给StackPanel1ButtonCreatedByCode_Click事件处理程序。
  5. 路由 Click 事件在元素树中继续向上传播,可能会触发分配给其他遍历元素的其他 Click 事件处理程序。

ButtonCreatedByCode_Click 事件处理程序获取有关触发它的事件的以下信息:

  • 发送方对象,它是事件处理程序分配给的元素。 处理程序首次运行时,senderButtonCreatedByCode,第二次运行时则为 StackPanel1
  • RoutedEventArgs.Source 对象,该对象是最初引发事件的元素。 在此示例中,Source 始终 ButtonCreatedByCode

注释

路由事件和 CLR 事件之间的一个关键区别在于,路由事件遍历元素树,查找处理程序,而 CLR 事件不会遍历元素树,处理程序只能附加到引发事件的源对象。 因此,路由事件 sender 可以是元素树中的任何遍历元素。

有关如何创建和处理路由事件的详细信息,请参阅 如何创建自定义路由事件处理路由事件

另请参阅