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

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

예제

WPF(Windows Presentation Foundation)에서 요소는 요소 트리 구조체에서 배열됩니다. 부모 요소는 초기에 요소 트리의 자식 요소에 의해 발생된 이벤트 처리에 참여할 수 있습니다. 이는 이벤트 라우팅으로 인해 가능합니다.

라우트된 이벤트는 일반적으로 두 가지 라우팅 전략(버블링 또는 터널링) 중 하나를 따릅니다. 이 예제에서는 버블링 이벤트에 초점을 맞추고 ButtonBase.Click 이벤트를 사용하여 라우팅의 작동 방식을 보여 줍니다.

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

부모 StackPanel 요소에서 특성으로 지정된 Click 이벤트 이름은 Button 클래스의 이름을 지정하여 부분적으로 정규화됩니다. Button 클래스는 해당 멤버 목록에서 Click 이벤트가 있는 ButtonBase 파생 클래스입니다. 처리중인 이벤트가 라우트된 이벤트 처리기가 연결된 요소의 멤버 목록에 있지 않은 경우 이벤트 처리기 연결을 위해 이러한 부분 한정 기술이 필요합니다.

<StackPanel
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://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 이벤트입니다. 이 예제에서는 이벤트를 처리하는 요소와 이벤트를 발생시키는 요소를 보여 줍니다. 이벤트 처리기는 두 버튼 중 하나를 클릭할 때 실행됩니다.

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();
    }
}
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

참고 항목