次の方法で共有


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

マークアップまたは分離コードを使用して、Windows Presentation Foundation (WPF) の要素にイベント ハンドラーを割り当てることができます。 Extensible Application Markup Language (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_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_Clickに割り当てられたButtonCreatedByCode イベント ハンドラーがトリガーされます。
  3. Clickルーティング イベントは、要素ツリーを上にたどってStackPanel1します。
  4. ButtonCreatedByCode_Clickに割り当てられたStackPanel1 イベント ハンドラーがトリガーされます。
  5. Clickルーティング イベントは、要素ツリーを上方に進みながら、他の走査された要素に割り当てられた他のClickイベント ハンドラーをトリガーする可能性があります。

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

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

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

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

こちらも参照ください