방법: 라우트된 이벤트 처리

업데이트: 2010년 7월

이 예제에서는 버블링 이벤트의 작동 방법 및 라우트된 이벤트 데이터를 처리할 수 있는 처리기를 작성하는 방법을 보여 줍니다.

예제

Windows Presentation Foundation (WPF)에서 요소는 이벤트 트리 구조 내에 정렬됩니다. 부모 요소는 요소 트리의 자식 요소에 의해 처음 발생한 이벤트의 처리에 참가할 수 있습니다. 이것이 가능한 것은 이벤트 라우팅 덕분입니다.

라우트된 이벤트는 일반적으로 버블링 또는 터널링이라는 두 라우팅 전략 중 하나를 따릅니다. 이 예제에서는 버블링 이벤트를 중점적으로 다루며 ButtonBase.Click 이벤트를 사용하여 라우팅의 작동 원리를 보여 줍니다.

다음 예제에서는 두 개의 Button 컨트롤을 만들고 XAML 특성 구문을 사용하여 공통 부모 요소인 StackPanel에 이벤트 처리기를 연결합니다. 이 예제에서는 각 Button 자식 요소에 대해 개별적으로 이벤트 처리기를 연결하는 대신 특성 구문을 사용하여 StackPanel 부모 요소에 이벤트 처리기를 연결합니다. 이 이벤트 처리 패턴은 이벤트 라우팅을 통해 처리기가 연결되는 요소의 수를 줄이는 방법을 보여 줍니다. 각 Button에 대한 모든 버블링 이벤트는 부모 요소를 통해 라우팅합니다.

부모 StackPanel 요소에서 특성으로 지정된 Click 이벤트 이름은 Button 클래스 이름을 지정하는 방식으로 부분적으로 정규화되어 있습니다. Button 클래스는 해당 멤버 목록에 Click 이벤트가 포함된 ButtonBase 파생 클래스입니다. 이벤트 처리기 연결을 위한 이와 같은 부분 정규화 기법은 라우트된 이벤트 처리기가 연결된 요소의 멤버 목록에 처리할 이벤트가 없는 경우 필요합니다.

<StackPanel
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="SDKSample.RoutedEventHandle"
  Name="dpanel"
  Button.Click="HandleClick"
>
  <StackPanel.Resources>
      <Style TargetType="{x:Type Button}">
        <Setter Property="Height" Value="20"/>
        <Setter Property="Width" Value="250"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
      </Style>
  </StackPanel.Resources>
  <Button Name="Button1">Item 1</Button>
  <Button Name="Button2">Item 2</Button>
  <TextBlock Name="results"/>
</StackPanel>
<StackPanel
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="SDKSample.RoutedEventHandle"
  Name="dpanel"
  Button.Click="HandleClick"
>
  <StackPanel.Resources>
      <Style TargetType="{x:Type Button}">
        <Setter Property="Height" Value="20"/>
        <Setter Property="Width" Value="250"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
      </Style>
  </StackPanel.Resources>
  <Button Name="Button1">Item 1</Button>
  <Button Name="Button2">Item 2</Button>
  <TextBlock Name="results"/>
</StackPanel>

다음 예제에서는 Click 이벤트를 처리합니다. 이 예제에서는 이벤트를 처리하는 요소와 이벤트를 발생시키는 요소를 보고합니다. 사용자가 단추를 클릭하면 이벤트 처리기가 실행됩니다.

Private eventstr As New Text.StringBuilder()

Private Sub HandleClick(ByVal sender As Object, ByVal args As RoutedEventArgs)
    ' Get the element that handled the event.
    Dim fe As FrameworkElement = DirectCast(sender, FrameworkElement)
    eventstr.Append("Event handled by element named ")
    eventstr.Append(fe.Name)
    eventstr.Append(vbLf)

    ' Get the element that raised the event. 
    Dim fe2 As FrameworkElement = DirectCast(args.Source, FrameworkElement)
    eventstr.Append("Event originated from source element of type ")
    eventstr.Append(args.Source.[GetType]().ToString())
    eventstr.Append(" with Name ")
    eventstr.Append(fe2.Name)
    eventstr.Append(vbLf)

    ' Get the routing strategy.
    eventstr.Append("Event used routing strategy ")
    eventstr.Append(args.RoutedEvent.RoutingStrategy)
    eventstr.Append(vbLf)

    results.Text = eventstr.ToString()
End Sub
public partial class RoutedEventHandle : StackPanel
{
    StringBuilder eventstr = new StringBuilder();
    void HandleClick(object sender, RoutedEventArgs args)
    {
        // Get the element that handled the event.
        FrameworkElement fe = (FrameworkElement)sender;
        eventstr.Append("Event handled by element named ");
        eventstr.Append(fe.Name);
        eventstr.Append("\n");

        // Get the element that raised the event. 
        FrameworkElement fe2 = (FrameworkElement)args.Source;
        eventstr.Append("Event originated from source element of type ");
        eventstr.Append(args.Source.GetType().ToString());
        eventstr.Append(" with Name ");
        eventstr.Append(fe2.Name);
        eventstr.Append("\n");

        // Get the routing strategy.
        eventstr.Append("Event used routing strategy ");
        eventstr.Append(args.RoutedEvent.RoutingStrategy);
        eventstr.Append("\n");

        results.Text = eventstr.ToString();
    }
}

참고 항목

참조

RoutedEvent

개념

입력 개요

라우트된 이벤트 개요

XAML 구문 정보

기타 리소스

이벤트 방법 항목

변경 기록

날짜

변경 내용

이유

2010년 7월

이벤트 처리기에 대한 예제를 추가했습니다.

고객 의견