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

此示例演示如何使用代码向元素添加事件处理程序。

如果要将事件处理程序添加到 XAML 元素,并且已加载包含该元素的标记页面,则必须使用代码添加处理程序。 或者,如果你完全使用代码为应用程序构建元素树,而不使用 XAML 声明任何元素,则可以调用特定方法将事件处理程序添加到构造的元素树。

示例

以下示例将新的 Button 添加到最初在 XAML 中定义的现有页面。 代码隐藏文件实现事件处理程序方法,然后将该方法添加为 Button 上的新事件处理程序。

C# 示例使用 += 运算符将处理程序分配给事件。 这与用于在公共语言运行时 (CLR) 事件处理模型中分配处理程序的运算符相同。 Microsoft Visual Basic 不支持将此运算符作为添加事件处理程序的一种方式。 相反,它需要以下两种技术之一:

  • 使用 AddHandler 方法和 AddressOf 运算符来引用事件处理程序实现。

  • 使用 Handles 关键字作为事件处理程序定义的一部分。 此处未说明此技术;请参阅 Visual Basic 和 WPF 事件处理

<TextBlock Name="text1">Start by clicking the button below</TextBlock>
<Button Name="b1" Click="MakeButton">Make new button and add handler to it</Button>
public partial class RoutedEventAddRemoveHandler {
    void MakeButton(object sender, RoutedEventArgs e)
    {
        Button b2 = new Button();
        b2.Content = "New Button";
        // Associate event handler to the button. You can remove the event
        // handler using "-=" syntax rather than "+=".
        b2.Click  += new RoutedEventHandler(Onb2Click);
        root.Children.Insert(root.Children.Count, b2);
        DockPanel.SetDock(b2, Dock.Top);
        text1.Text = "Now click the second button...";
        b1.IsEnabled = false;
    }
    void Onb2Click(object sender, RoutedEventArgs e)
    {
        text1.Text = "New Button (b2) Was Clicked!!";
    }
Public Partial Class RoutedEventAddRemoveHandler
    Private Sub MakeButton(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim b2 As Button = New Button()
        b2.Content = "New Button"
        AddHandler b2.Click, AddressOf Onb2Click
        root.Children.Insert(root.Children.Count, b2)
        DockPanel.SetDock(b2, Dock.Top)
        text1.Text = "Now click the second button..."
        b1.IsEnabled = False
    End Sub
    Private Sub Onb2Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        text1.Text = "New Button (b2) Was Clicked!!"
    End Sub

注意

在最初解析的 XAML 页面中添加事件处理程序要简单得多。 在要添加事件处理程序的对象元素中,添加与要处理的事件名称一致的属性。 然后将该属性的值指定为你在 XAML 页面的代码隐藏文件中定义的事件处理程序方法的名称。 有关更多信息,请参阅 WPF 中的 XAML路由事件概述

另请参阅