방법: 사용자 지정 라우트된 이벤트 만들기

사용자 지정 이벤트에서 이벤트 라우팅을 지원하려면 RegisterRoutedEvent 메서드를 사용하여 RoutedEvent를 등록해야 합니다. 이 예제에서는 사용자 지정 라우트된 이벤트를 만드는 데 대한 기본 사항을 설명합니다.

예제

다음 예제와 같이 먼저 RegisterRoutedEvent를 사용하여 RoutedEvent를 등록합니다. 규칙에 따라 RoutedEvent 정적 필드 이름은 Event 접미사로 끝나야 합니다. 이 예제에서 이벤트의 이름은 Tap이고 이벤트의 라우팅 전략은 Bubble입니다. 등록 호출 후에는 이벤트에 대한 추가 및 제거 CLR(공용 언어 런타임) 이벤트 접근자를 제공할 수 있습니다.

이 예제에서는 OnTap이라는 가상 메서드를 통해 이벤트를 발생시키지만 이벤트를 발생시키는 방법 및 이벤트가 변경에 응답하는 방법은 필요에 맞게 설정할 수 있습니다.

또한 이 예제에서는 기본적으로 Button의 서브클래스 전체를 구현합니다. 즉, 이 서브클래스를 별도의 어셈블리로 빌드한 후 별도의 XAML 페이지에 사용자 지정 클래스로 인스턴스화합니다. 이는 다른 컨트롤로 구성된 트리에 서브클래싱된 컨트롤을 삽입할 수 있고, 이 경우 이러한 컨트롤의 사용자 지정 이벤트의 이벤트 라우팅 기능이 모든 네이티브 WPF 요소의 이벤트 라우팅 기능과 동일하다는 점을 보여 주기 위함입니다.

public class MyButtonSimple: Button
{
    // Create a custom routed event by first registering a RoutedEventID
    // This event uses the bubbling routing strategy
    public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
        "Tap", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButtonSimple));

    // Provide CLR accessors for the event
    public event RoutedEventHandler Tap
    {
            add { AddHandler(TapEvent, value); }
            remove { RemoveHandler(TapEvent, value); }
    }

    // This method raises the Tap event
    void RaiseTapEvent()
    {
            RoutedEventArgs newEventArgs = new RoutedEventArgs(MyButtonSimple.TapEvent);
            RaiseEvent(newEventArgs);
    }
    // For demonstration purposes we raise the event when the MyButtonSimple is clicked
    protected override void OnClick()
    {
        RaiseTapEvent();
    }
}
Public Class MyButtonSimple
    Inherits Button

    ' Create a custom routed event by first registering a RoutedEventID
    ' This event uses the bubbling routing strategy
    Public Shared ReadOnly TapEvent As RoutedEvent = EventManager.RegisterRoutedEvent("Tap", RoutingStrategy.Bubble, GetType(RoutedEventHandler), GetType(MyButtonSimple))

    ' Provide CLR accessors for the event
    Public Custom Event Tap As RoutedEventHandler
        AddHandler(ByVal value As RoutedEventHandler)
            Me.AddHandler(TapEvent, value)
        End AddHandler

        RemoveHandler(ByVal value As RoutedEventHandler)
            Me.RemoveHandler(TapEvent, value)
        End RemoveHandler

        RaiseEvent(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Me.RaiseEvent(e)
        End RaiseEvent
    End Event

    ' This method raises the Tap event
    Private Sub RaiseTapEvent()
        Dim newEventArgs As New RoutedEventArgs(MyButtonSimple.TapEvent)
        MyBase.RaiseEvent(newEventArgs)
    End Sub

    ' For demonstration purposes we raise the event when the MyButtonSimple is clicked
    Protected Overrides Sub OnClick()
        Me.RaiseTapEvent()
    End Sub

End Class
<Window  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:SDKSample;assembly=SDKSampleLibrary"
    x:Class="SDKSample.RoutedEventCustomApp"

    >
    <Window.Resources>
      <Style TargetType="{x:Type custom:MyButtonSimple}">
        <Setter Property="Height" Value="20"/>
        <Setter Property="Width" Value="250"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
        <Setter Property="Background" Value="#808080"/>
      </Style>
    </Window.Resources>
    <StackPanel Background="LightGray">
        <custom:MyButtonSimple Name="mybtnsimple" Tap="TapHandler">Click to see Tap custom event work</custom:MyButtonSimple>
    </StackPanel>
</Window>

터널링 이벤트는 같은 방식으로 만들어지지만, 등록 호출에서 RoutingStrategyTunnel로 설정됩니다. 규칙에 따라 WPF의 터널링 이벤트에는 “Preview”라는 접두사가 추가됩니다.

버블링 이벤트 작동 방식에 대한 예제를 보려면 라우트된 이벤트 처리를 참조하세요.

참고 항목