コードを使用してイベント ハンドラーを追加する方法 (WPF .NET)

マークアップまたは分離コードを使用して、Windows Presentation Foundation (WPF) 内の要素にイベント ハンドラーを割り当てることができます。 通常は Extensible Application Markup Language (XAML) でイベント ハンドラーを割り当てますが、分離コードでイベント ハンドラーを割り当てる必要がある場合もあります。 たとえば、次のような場合にコードを使用します。

  • 要素を含むマークアップ ページの読み込み後に、イベント ハンドラーを要素に割り当てます。
  • 要素を追加し、要素を含むマークアップ ページの読み込み後にイベント ハンドラーを割り当てます。
  • アプリケーションの要素ツリーを、コード内で完全に定義します。

重要

.NET 7 と .NET 6 用のデスクトップ ガイド ドキュメントは作成中です。

前提条件

この記事では、ルーティング イベントの基本的な知識があり、「ルーティング イベントの概要」をお読みになったことを前提としています。 この記事の例について理解するには、Extensible Application Markup Language (XAML) を使い慣れていて、Windows Presentation Foundation (WPF) アプリケーションの記述方法を理解していると役に立ちます。

イベント ハンドラーの割り当ての構文

C# では、次を使用したイベント ハンドラーの割り当てがサポートされています。

  • += 演算子。これは、共通言語ランタイム (CLR) イベント処理モデルでも使用されます。
  • UIElement.AddHandler メソッド。

VB では、次を使用したイベント ハンドラーの割り当てがサポートされています。

次の例では、XAML を使用して ButtonCreatedByXaml という名前の Button を定義し、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_Click ハンドラーを ButtonCreatedByCode 要素と StackPanel1 要素に割り当てます。 イベント ハンドラー メソッドは、分離コードでのみ実装できます。

// 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. 既に構築されている XAML 要素ツリーに、ButtonCreatedByCode という名前の新しいボタンを追加します。
  2. 名前、コンテンツ、背景色など、新しいボタンのプロパティを指定します。
  3. ButtonCreatedByCode_Click イベント ハンドラーを ButtonCreatedByCode に割り当てます。
  4. 同じ ButtonCreatedByCode_Click イベント ハンドラーを StackPanel1 に割り当てます。

ButtonCreatedByCode がクリックされた場合、次の処理が実行されます。

  1. Click ルーティング イベントが ButtonCreatedByCode で発生します。
  2. ButtonCreatedByCode に割り当てられた ButtonCreatedByCode_Click イベント ハンドラーがトリガーされます。
  3. Click ルーティング イベントでは、要素ツリーが StackPanel1 まで検査されます。
  4. StackPanel1 に割り当てられた ButtonCreatedByCode_Click イベント ハンドラーがトリガーされます。
  5. Click ルーティング イベントは要素ツリー上で継続され、他の検査対象要素に割り当てられた他の Click イベント ハンドラーがトリガーされる可能性があります。

ButtonCreatedByCode_Click イベント ハンドラーは、トリガーしたイベントに関する次の情報を取得します。

  • イベント ハンドラーが割り当てられた要素である sender オブジェクト。 sender は、ハンドラーが初めて実行されたときは ButtonCreatedByCode、2 回目は StackPanel1 になります。
  • 最初にイベントを発生させた要素である RoutedEventArgs.Source オブジェクト。 この例では、Source は常に ButtonCreatedByCode です。

注意

ルーティング イベントと CLR イベントの主な違いは、ルーティング イベントでは要素ツリーを検査してハンドラーを探すのに対し、CLR イベントでは要素ツリーを検査せず、ハンドラーはイベントを発生させたソース オブジェクトにのみアタッチできることです。 その結果、sender ルーティング イベントには、要素ツリー内の任意の検査対象要素を指定できます。

ルーティング イベントを作成して処理する方法の詳細については、「カスタム ルーティング イベントを作成する方法」と「ルーティング イベントを処理する」を参照してください。

参照