如何使用程式碼新增事件處理常式 (WPF .NET)

您可以使用標記或程式碼後置,將事件處理常式指派給 Windows Presentation Foundation (WPF) 中的專案。 雖然在 Extensible Application Markup Language (XAML) 中指派事件處理常式是慣用的,但有時候您可能需要在程式碼後置中指派事件處理常式。 例如,在下列情況下使用程式碼:

  • 您可以在包含元素載入的標記頁面之後,將事件處理常式指派給專案。
  • 您可以在包含元素載入的標記頁面之後,新增元素並指派其事件處理常式。
  • 您可以在程式碼中完全定義應用程式的元素樹狀結構。

重要

.NET 7 和 .NET 6 的桌面指南檔正在建置中。

必要條件

本文假設您已瞭解路由事件,而且您已閱讀 路由事件概觀 。 若要遵循本文中的範例,如果您熟悉可延伸的應用程式標記語言(XAML),並知道如何撰寫 Windows Presentation Foundation (WPF) 應用程式,它很有説明。

事件處理常式指派的語法

C# 支援使用下列專案來指派事件處理常式:

  • 運算子 += ,也用於 Common Language Runtime (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_Click 作 和 ButtonCreatedByCode_Click 處理常式,並將處理常式指派 ButtonCreatedByCode_ClickButtonCreatedByCodeStackPanel1 元素。 事件處理常式方法只能在程式碼後置中實作。

// 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

按一下 ButtonCreatedByXaml 時,其事件處理常式會以程式設計方式執行 ButtonCreatedByXaml_Click

  1. 將名為 ButtonCreatedByCode 的新按鈕新增至已建構的 XAML 專案樹狀結構。
  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事件處理常式會取得下列觸發事件的相關資訊:

  • sender 物件,這是指派事件處理常式的專案。 將是 senderButtonCreatedByCode 處理常式第一次執行,第 StackPanel1 二次。
  • 物件 RoutedEventArgs.Source ,這是原本引發事件的專案。 在此範例中,一 SourceButtonCreatedByCode 為 。

注意

路由事件與 CLR 事件之間的主要差異在於路由事件會周遊專案樹狀結構,尋找處理常式,而 CLR 事件不會周遊專案樹狀結構,而且處理常式只能附加至引發事件的來源物件。 因此,路由事件 sender 可以是專案樹狀結構中的任何周遊專案。

如需如何建立及處理路由事件的詳細資訊,請參閱 如何建立自訂路由事件 處理路由事件

另請參閱