코드를 사용하여 이벤트 처리기를 추가하는 방법(WPF .NET)

태그 또는 코드 숨김을 사용하여 WPF(Windows Presentation Foundation)에서 요소에 이벤트 처리기를 할당할 수 있습니다. XAML(Extensible Application Markup Language)에서 이벤트 처리기를 할당하는 것이 관례이지만 코드 숨김에서 이벤트 처리기를 할당해야 하는 경우도 있습니다. 예를 들어 다음 경우에는 코드를 사용하세요.

  • 요소 로드가 포함된 태그 페이지 뒤의 요소에 이벤트 처리기를 할당하는 경우
  • 요소를 추가하고 요소 로드를 포함할 태그 페이지 뒤에 해당 이벤트 처리기를 할당하는 경우
  • 애플리케이션의 요소 트리를 전적으로 코드로 정의하는 경우

중요

.NET 7 및 .NET 6에 관한 데스크톱 가이드 설명서는 제작 중입니다.

필수 구성 요소

이 문서에서는 독자들이 라우트된 이벤트에 대한 기본 지식을 갖고 있으며 라우트된 이벤트 개요를 읽었다고 가정합니다. XAML(Extensible Application Markup Language)에 익숙하고 WPF(Windows Presentation Foundation) 애플리케이션을 작성하는 방법을 알고 있으면 이 문서의 예제를 따라 하는 데 도움이 됩니다.

이벤트 처리기 할당 구문

C#은 다음을 사용한 이벤트 처리기 할당을 지원합니다.

  • CLR(공용 언어 런타임) 이벤트 처리 모델에서도 사용되는 += 연산자
  • UIElement.AddHandler 메서드

VB는 다음을 사용한 이벤트 처리기 할당을 지원합니다.

예제

다음 예제는 XAML을 사용하여 이름이 ButtonCreatedByXamlButton을 정의하고 ButtonCreatedByXaml_Click 메서드를 해당 Click 이벤트 처리기로 할당합니다. ClickButtonBase에서 파생되는 단추의 기본 제공 라우트된 이벤트입니다.

<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

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는 처리기가 처음 실행될 때 ButtonCreatedByCode가 되고 두 번째 실행될 때 StackPanel1이 됩니다.
  • 원래 이벤트를 발생시킨 RoutedEventArgs.Source 개체 이 예제에서 Source는 항상 ButtonCreatedByCode입니다.

참고

라우트된 이벤트와 CLR 이벤트의 주요 차이점은 라우트된 이벤트가 요소 트리를 트래버스하여 처리기를 찾는 반면 CLR 이벤트는 요소 트리를 트래버스하지 않으며 처리기는 이벤트를 발생시킨 원본 개체에만 연결할 수 있다는 것입니다. 따라서 라우트된 이벤트 sender는 요소 트리의 모든 트래버스된 요소일 수 있습니다.

라우트된 이벤트를 만들고 처리하는 방법에 대한 자세한 내용은 사용자 지정 라우트된 이벤트를 만드는 방법라우트된 이벤트 처리를 참조하세요.

추가 정보