Visão geral sobre eventos roteados

This topic describes the concept of routed events in Windows Presentation Foundation (WPF). O tópico define a terminologia de eventos roteados, descreve como eventos roteados são roteados por meio de uma árvore de elementos, resume como lidar com eventos roteados e apresenta como criar seus próprios eventos roteados personalizados.

Este tópico contém as seguintes seções.

  • Prerequisites
  • What Is a Routed Event?
  • Routing Strategies
  • Why Use Routed Events?
  • Adding and Implementing an Event Handler for a Routed Event
  • Class Handlers
  • Attached Events in WPF
  • Qualified Event Names in XAML
  • WPF Input Events
  • EventSetters and EventTriggers
  • More About Routed Events
  • Tópicos relacionados

Prerequisites

This topic assumes that you have basic knowledge of the common language runtime (CLR) and object-oriented programming, as well as the concept of how the relationships between WPF elements can be conceptualized as a tree. In order to follow the examples in this topic, you should also understand Extensible Application Markup Language (XAML) and know how to write very basic WPF applications or pages. For more information, see Demonstra Passo a passo: Guia de Introdução do WPF and Visão geral do XAML (WPF).

What Is a Routed Event?

You can think about routed events either from a functional or implementation perspective. Both definitions are presented here, because some people find one or the other definition more useful.

Definição funcional: Um evento roteado é um tipo de evento pode chamar manipuladores em vários ouvintes em uma árvore de elemento, em vez de apenas no objeto que disparou o evento.

Definição de implementação: A roteadas evento é um CLR evento que é feito por uma instância da RoutedEvent de classe e é processada pelo Windows Presentation Foundation (WPF) sistema de eventos.

Uma típica WPF aplicativo contém muitos elementos. Se criado no código ou declarado em XAML, esses elementos existem em um relacionamento de árvore de elemento uns aos outros. The event route can travel in one of two directions depending on the event definition, but generally the route travels from the source element and then "bubbles" upward through the element tree until it reaches the element tree root (typically a page or a window). This bubbling concept might be familiar to you if you have worked with the DHTML object model previously.

Consider the following simple element tree:

<Border Height="50" Width="300" BorderBrush="Gray" BorderThickness="1">
  <StackPanel Background="LightGray" Orientation="Horizontal" Button.Click="CommonClickHandler">
    <Button Name="YesButton" Width="Auto" >Yes</Button>
    <Button Name="NoButton" Width="Auto" >No</Button>
    <Button Name="CancelButton" Width="Auto" >Cancel</Button>
  </StackPanel>
</Border>

This element tree produces something like the following:

Botões Sim, Não e Cancelar

In this simplified element tree, the source of a Click event is one of the Button elements, and whichever Button was clicked is the first element that has the opportunity to handle the event. But if no handler attached to the Button acts on the event, then the event will bubble upwards to the Button parent in the element tree, which is the StackPanel. Potentially, the event bubbles to Border, and then beyond to the page root of the element tree (not shown).

In other words, the event route for this Click event is:

Button-->StackPanel-->Border-->...

Top-level Scenarios for Routed Events

The following is a brief summary of the scenarios that motivated the routed event concept, and why a typical CLR event was not adequate for these scenarios:

Controle de composição e encapsulamento: Vários controles em WPF tem um modelo de conteúdo rico. For example, you can place an image inside of a Button, which effectively extends the visual tree of the button. However, the added image must not break the hit-testing behavior that causes a button to respond to a Click of its content, even if the user clicks on pixels that are technically part of the image.

Pontos de fixação do manipulador singular: Em Windows Forms, você terá que anexar o mesmo manipulador várias vezes para eventos de processo que podem ser gerados a partir de vários elementos. Routed events enable you to attach that handler only once, as was shown in the previous example, and use handler logic to determine where the event came from if necessary. For instance, this might be the handler for the previously shown XAML:

      Private Sub CommonClickHandler(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim feSource As FrameworkElement = TryCast(e.Source, FrameworkElement)
        Select Case feSource.Name
          Case "YesButton"
            ' do something here ...
          Case "NoButton"
            ' do something ...
          Case "CancelButton"
            ' do something ...
        End Select
        e.Handled=True
      End Sub
private void CommonClickHandler(object sender, RoutedEventArgs e)
{
  FrameworkElement feSource = e.Source as FrameworkElement;
  switch (feSource.Name)
  {
    case "YesButton":
      // do something here ...
      break;
    case "NoButton":
      // do something ...
      break;
    case "CancelButton":
      // do something ...
      break;
  }
  e.Handled=true;
}

Tratamento de classe: Roteadas eventos permitir um manipulador estático que é definido pela classe. This class handler has the opportunity to handle an event before any attached instance handlers can.

Um evento sem reflexo de referência: Determinadas técnicas de código e marcação exigem uma maneira de identificar um evento específico. A routed event creates a RoutedEvent field as an identifier, which provides a robust event identification technique that does not require static or run-time reflection.

How Routed Events Are Implemented

A roteadas evento é um CLR evento que é feito por uma instância da RoutedEvent de classe e registrado com o WPF sistema de eventos. The RoutedEvent instance obtained from registration is typically retained as a public static readonly field member of the class that registers and thus "owns" the routed event. A conexão com nomes idênticos CLR evento (que é às vezes chamados de "empacotador" evento) é conseguido substituindo o add e remove implementações para o CLR de evento. Normalmente, o add e remove são deixados como um padrão implícito que usa a sintaxe do evento de específicos do idioma apropriado para adicionar e remover manipuladores de eventos. O mecanismo de backup e conexão de evento roteado é conceitualmente semelhante a como um propriedade de dependência é um CLR propriedade tem o respaldo de DependencyProperty de classe e registrado com o WPF propriedade system.

The following example shows the declaration for a custom Tap routed event, including the registration and exposure of the RoutedEvent identifier field and the add and remove implementations for the Tap CLR event.

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

Routed Event Handlers and XAML

To add a handler for an event using XAML, you declare the event name as an attribute on the element that is an event listener. The value of the attribute is the name of your implemented handler method, which must exist in the partial class of the code-behind file.

<Button Click="b1SetColor">button</Button>

O XAML sintaxe para adicionar um padrão CLR manipuladores de eventos é o mesmo para adicionar manipuladores de eventos roteados, porque você está realmente Adicionando manipuladores para o CLR wrapper do evento, que tem um evento roteado implementação sob. For more information about adding event handlers in XAML, see Visão geral do XAML (WPF).

Routing Strategies

Routed events use one of three routing strategies:

  • Propagação: Os manipuladores de eventos na fonte de evento são invocados. The routed event then routes to successive parent elements until reaching the element tree root. Most routed events use the bubbling routing strategy. Bubbling routed events are generally used to report input or state changes from distinct controls or other UI elements.

  • Direto: O elemento de origem própria tem a oportunidade de chamar manipuladores de resposta. This is analogous to the "routing" that Windows Forms uses for events. No entanto, diferentemente de um padrão CLR evento, direcionar o tratamento de classe de suporte a eventos roteados (manipulação de classe é explicada em uma seção de futura) e pode ser usada por EventSetter e EventTrigger.

  • Encapsulamento: Inicialmente, os manipuladores de eventos na raiz da árvore de elemento são invocados. The routed event then travels a route through successive child elements along the route, towards the node element that is the routed event source (the element that raised the routed event). Tunneling routed events are often used or handled as part of the compositing for a control, such that events from composite parts can be deliberately suppressed or replaced by events that are specific to the complete control. Input events provided in WPF often come implemented as a tunneling/bubbling pair. Tunneling events are also sometimes referred to as Preview events, because of a naming convention that is used for the pairs.

Why Use Routed Events?

As an application developer, you do not always need to know or care that the event you are handling is implemented as a routed event. Routed events have special behavior, but that behavior is largely invisible if you are handling an event on the element where it is raised.

Onde os eventos roteados se tornam poderosos é se você usar qualquer um dos cenários sugeridos: Definindo manipuladores comuns em uma raiz comum, compondo seu próprio controle ou definir sua própria classe de controle personalizado.

Routed event listeners and routed event sources do not need to share a common event in their hierarchy. Any UIElement or ContentElement can be an event listener for any routed event. Therefore, you can use the full set of routed events available throughout the working API set as a conceptual "interface" whereby disparate elements in the application can exchange event information. This "interface" concept for routed events is particularly applicable for input events.

Routed events can also be used to communicate through the element tree, because the event data for the event is perpetuated to each element in the route. One element could change something in the event data, and that change would be available to the next element in the route.

Other than the routing aspect, there are two other reasons that any given WPF event might be implemented as a routed event instead of a standard CLR event. If you are implementing your own events, you might also consider these principles:

  • Certas WPF recursos de modelagem e os estilos, como EventSetter e EventTrigger exigirá que o evento referenciado para ser um evento roteado. This is the event identifier scenario mentioned earlier.

  • Routed events support a class handling mechanism whereby the class can specify static methods that have the opportunity to handle routed events before any registered instance handlers can access them. This is very useful in control design, because your class can enforce event-driven class behaviors that cannot be accidentally suppressed by handling an event on an instance.

Each of the above considerations is discussed in a separate section of this topic.

Adding and Implementing an Event Handler for a Routed Event

To add an event handler in XAML, you simply add the event name to an element as an attribute and set the attribute value as the name of the event handler that implements an appropriate delegate, as in the following example.

<Button Click="b1SetColor">button</Button>

b1SetColor é o nome do manipulador implementado que contém o código que manipula a Click de evento. b1SetColor deve ter a mesma assinatura que o RoutedEventHandler delegado, que é delegado do manipulador de eventos para o Click de evento. The first parameter of all routed event handler delegates specifies the element to which the event handler is added, and the second parameter specifies the data for the event.

      Private Sub b1SetColor(ByVal sender As Object, ByVal args As RoutedEventArgs)
        'logic to handle the Click event


...


      End Sub
void b1SetColor(object sender, RoutedEventArgs args)
{
  //logic to handle the Click event


...


}

RoutedEventHandler is the basic routed event handler delegate. For routed events that are specialized for certain controls or scenarios, the delegates to use for the routed event handlers also might become more specialized, so that they can transmit specialized event data. For instance, in a common input scenario, you might handle a DragEnter routed event. Your handler should implement the DragEventHandler delegate. By using the most specific delegate, you can process the DragEventArgs in the handler and read the Data property, which contains the clipboard payload of the drag operation.

For a complete example of how to add an event handler to an element using XAML, see Como: Handle a Routed Event.

Adding a handler for a routed event in an application that is created in code is straightforward. Routed event handlers can always be added through a helper method AddHandler (which is the same method that the existing backing calls for add.) However, existing WPF routed events generally have backing implementations of add and remove logic that allow the handlers for routed events to be added by a language-specific event syntax, which is more intuitive syntax than the helper method. The following is an example usage of the helper method:

       Private Sub MakeButton()
            Dim b2 As New Button()
            b2.AddHandler(Button.ClickEvent, New RoutedEventHandler(AddressOf Onb2Click))
       End Sub
        Private Sub Onb2Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            'logic to handle the Click event     
        End Sub
void MakeButton()
 {
     Button b2 = new Button();
     b2.AddHandler(Button.ClickEvent, new RoutedEventHandler(Onb2Click));
 }
 void Onb2Click(object sender, RoutedEventArgs e)
 {
     //logic to handle the Click event     
 }

The next example shows the C# operator syntax (Visual Basic has slightly different operator syntax because of its handling of dereferencing):

        Private Sub MakeButton2()
          Dim b2 As New Button()
          AddHandler b2.Click, AddressOf Onb2Click2
        End Sub
        Private Sub Onb2Click2(ByVal sender As Object, ByVal e As RoutedEventArgs)
          'logic to handle the Click event     
        End Sub
void MakeButton2()
{
  Button b2 = new Button();
  b2.Click += new RoutedEventHandler(Onb2Click2);
}
void Onb2Click2(object sender, RoutedEventArgs e)
{
  //logic to handle the Click event     
}

For an example of how to add an event handler in code, see Como: Adicionar um manipulador de eventos usando código.

If you are using Visual Basic, you can also use the Handles keyword to add handlers as part of the handler declarations. For more information, see Visual Basic and WPF Event Handling.

The Concept of Handled

Todos os eventos roteados compartilham uma evento dados classe base comum, RoutedEventArgs. RoutedEventArgsDefine o Handled propriedade, que usa um valor booleano. The purpose of the Handled property is to enable any event handler along the route to mark the routed event as handled, by setting the value of Handled to true. After being processed by the handler at one element along the route, the shared event data is again reported to each listener along the route.

The value of Handled affects how a routed event is reported or processed as it travels further along the route. If Handled is true in the event data for a routed event, then handlers that listen for that routed event on other elements are generally no longer invoked for that particular event instance. Isso é verdadeiro para manipuladores anexado no XAML e para manipuladores adicionados por sintaxes de anexo de manipulador de evento específico do idioma, como += ou Handles. Para cenários mais comuns do manipulador, marcar um evento como manipulado, definindo Handled para true será "stop" o roteamento para uma rota de encapsulamento ou de uma rota bubbling e também para qualquer evento que é tratado por um manipulador de classe em um ponto no roteiro.

However, there is a "handledEventsToo" mechanism whereby listeners can still run handlers in response to routed events where Handled is true in the event data. In other words, the event route is not truly stopped by marking the event data as handled. You can only use the handledEventsToo mechanism in code, or in an EventSetter:

In addition to the behavior that Handled state produces in routed events, the concept of Handled has implications for how you should design your application and write the event handler code. You can conceptualize Handled as being a simple protocol that is exposed by routed events. Exactly how you use this protocol is up to you, but the conceptual design for how the value of Handled is intended to be used is as follows:

  • If a routed event is marked as handled, then it does not need to be handled again by other elements along that route.

  • If a routed event is not marked as handled, then other listeners that were earlier along the route have chosen either not to register a handler, or the handlers that were registered chose not to manipulate the event data and set Handled to true. (Or, it is of course possible that the current listener is the first point in the route.) Handlers on the current listener now have three possible courses of action:

    • Take no action at all; the event remains unhandled, and the event routes to the next listener.

    • Execute code in response to the event, but make the determination that the action taken was not substantial enough to warrant marking the event as handled. The event routes to the next listener.

    • Execute code in response to the event. Mark the event as handled in the event data passed to the handler, because the action taken was deemed substantial enough to warrant marking as handled. The event still routes to the next listener, but with Handled=true in its event data, so only handledEventsToo listeners have the opportunity to invoke further handlers.

Este design conceitual é reforçado pelo comportamento de roteamento mencionado anteriormente: é mais difícil (embora ainda é possível no código ou estilos) anexar manipuladores de eventos roteados que são invocados mesmo se já definiu um manipulador anterior ao longo da rota Handled para true.

For more information about Handled, class handling of routed events, and recommendations about when it is appropriate to mark a routed event as Handled, see Marcando Eventos Roteados como Manipulados e Manipulação de Classes.

In applications, it is quite common to just handle a bubbling routed event on the object that raised it, and not be concerned with the event's routing characteristics at all. However, it is still a good practice to mark the routed event as handled in the event data, to prevent unanticipated side effects just in case an element that is further up the element tree also has a handler attached for that same routed event.

Class Handlers

If you are defining a class that derives in some way from DependencyObject, you can also define and attach a class handler for a routed event that is a declared or inherited event member of your class. Class handlers are invoked before any instance listener handlers that are attached to an instance of that class, whenever a routed event reaches an element instance in its route.

Alguns WPF controles têm tratamento de classe inerente roteado para determinados eventos. Isso pode dar a aparência para fora do que o evento roteado nunca não foi gerado, mas na realidade, ele está sendo tratado de classe e o evento roteado potencialmente ainda pode ser tratado por seus manipuladores de instância se você usar determinadas técnicas. Also, many base classes and controls expose virtual methods that can be used to override class handling behavior. For more information both on how to work around undesired class handling and on defining your own class handling in a custom class, see Marcando Eventos Roteados como Manipulados e Manipulação de Classes.

Attached Events in WPF

O XAML idioma também define um tipo especial de evento chamado um anexado evento. An attached event enables you to add a handler for a particular event to an arbitrary element. O elemento manipulando o evento não precisa definir ou herdar o evento anexado e nem o objeto potencialmente aumentando o evento nem o instância de manipulação de destino deve definir ou caso contrário "próprios" Esse evento como um membro de classe.

O WPF sistema de entrada usa eventos anexados extensivamente. However, nearly all of these attached events are forwarded through base elements. The input events then appear as equivalent non-attached routed events that are members of the base element class. For instance, the underlying attached event Mouse.MouseDown can more easily be handled on any given UIElement by using MouseDown on that UIElement rather than dealing with attached event syntax either in XAML or code.

For more information about attached events in WPF, see Visão geral sobre eventos anexados.

Qualified Event Names in XAML

Another syntax usage that resembles typename.eventname attached event syntax but is not strictly speaking an attached event usage is when you attach handlers for routed events that are raised by child elements. You attach the handlers to a common parent, to take advantage of event routing, even though the common parent might not have the relevant routed event as a member. Consider this example again:

<Border Height="50" Width="300" BorderBrush="Gray" BorderThickness="1">
  <StackPanel Background="LightGray" Orientation="Horizontal" Button.Click="CommonClickHandler">
    <Button Name="YesButton" Width="Auto" >Yes</Button>
    <Button Name="NoButton" Width="Auto" >No</Button>
    <Button Name="CancelButton" Width="Auto" >Cancel</Button>
  </StackPanel>
</Border>

Here, the parent element listener where the handler is added is a StackPanel. However, it is adding a handler for a routed event that was declared and will be raised by the Button class (ButtonBase actually, but available to Button through inheritance). Button "owns" the event, but the routed event system permits handlers for any routed event to be attached to any UIElement or ContentElement instance listener that could otherwise attach listeners for a common language runtime (CLR) event. O namespace padrão xmlns desses nomes de atributo de evento qualificado geralmente é o padrão WPF namespace xmlns, mas você também pode especificar o prefixo de namespaces para eventos roteados personalizados. For more information about xmlns, see Namespaces XAML e o mapeamento de Namespace para WPF XAML.

WPF Input Events

Um aplicativo freqüente de eventos roteados dentro do WPF plataforma é para eventos de entrada. Em WPF, o encapsulamento roteadas eventos nomes são prefixados com a palavra "Visualização" Por convenção. Input events often come in pairs, with one being the bubbling event and the other being the tunneling event. For example, the KeyDown event and the PreviewKeyDown event have the same signature, with the former being the bubbling input event and the latter being the tunneling input event. Occasionally, input events only have a bubbling version, or perhaps only a direct routed version. Na documentação do evento roteado tópicos referência cruzada eventos roteados similares com estratégias alternativas de roteamento se existirem de tais eventos roteados e seções nas páginas de referência gerenciada esclarecem a estratégia de roteamento de cada evento roteado.

WPF input events that come in pairs are implemented so that a single user action from input, such as a mouse button press, will raise both routed events of the pair in sequence. First, the tunneling event is raised and travels its route. Then the bubbling event is raised and travels its route. Os dois eventos compartilham literalmente a mesma instância de dados de eventos, porque o RaiseEvent chamada de método na classe de implementação que dispara o evento bubbling escuta os dados de evento a partir do evento de encapsulamento e reutiliza do novo evento elevado. Ouvintes de manipuladores de evento de encapsulamento tem a primeira oportunidade para marcar o evento roteado manipulado (manipuladores de classe em primeiro lugar, em seguida, instância manipuladores). Se um elemento na rota de encapsulamento marcado o evento roteado como manipulado, os dados do evento já tratado é enviados para o evento bubbling e típicos manipuladores anexados para o equivalente a subida de eventos de entrada não serão chamados. To outward appearances it will be as if the handled bubbling event has not even been raised. This handling behavior is useful for control compositing, where you might want all hit-test based input events or focus-based input events to be reported by your final control, rather than its composite parts. The final control element is closer to the root in the compositing, and therefore has the opportunity to class handle the tunneling event first and perhaps to "replace" that routed event with a more control-specific event, as part of the code that backs the control class.

As an illustration of how input event processing works, consider the following input event example. In the following tree illustration, leaf element #2 is the source of both a PreviewMouseDown and then a MouseDown event.

Input Event Bubbling and Tunneling

Diagrama de roteamento de eventos

The order of event processing is as follows:

  1. PreviewMouseDown (tunnel) on root element.

  2. PreviewMouseDown (tunnel) on intermediate element #1.

  3. PreviewMouseDown (tunnel) on source element #2.

  4. MouseDown (bubble) on source element #2.

  5. MouseDown (bubble) on intermediate element #1.

  6. MouseDown (bubble) on root element.

Um delegado manipulador de eventos roteados fornece referências para dois objetos: o objeto que disparou o evento e o objeto onde o manipulador foi chamado. The object where the handler was invoked is the object reported by the sender parameter. The object where the event was first raised is reported by the Source property in the event data. A routed event can still be raised and handled by the same object, in which case sender and Source are identical (this is the case with Steps 3 and 4 in the event processing example list).

Because of tunneling and bubbling, parent elements receive input events where the Source is one of their child elements. When it is important to know what the source element is, you can identify the source element by accessing the Source property.

Usually, once the input event is marked Handled, further handlers are not invoked. Typically, you should mark input events as handled as soon as a handler is invoked that addresses your application-specific logical handling of the meaning of the input event.

The exception to this general statement about Handled state is that input event handlers that are registered to deliberately ignore Handled state of the event data would still be invoked along either route. For more information, see Visualização de Eventos or Marcando Eventos Roteados como Manipulados e Manipulação de Classes.

The shared event data model between tunneling and bubbling events, and the sequential raising of first tunneling then bubbling events, is not a concept that is generally true for all routed events. Que o comportamento é especificamente implementado por como WPF dispositivos de entrada optar por aumentar e conectar o pares de evento de entrada. Implementing your own input events is an advanced scenario, but you might choose to follow that model for your own input events also.

Certain classes choose to class-handle certain input events, usually with the intent of redefining what a particular user-driven input event means within that control and raising a new event. For more information, see Marcando Eventos Roteados como Manipulados e Manipulação de Classes.

For more information on input and how input and events interact in typical application scenarios, see Input Overview.

EventSetters and EventTriggers

In styles, you can include some pre-declared XAML event handling syntax in the markup by using an EventSetter. When the style is applied, the referenced handler is added to the styled instance. Você pode declarar um EventSetter somente para um evento roteado. A seguir é um exemplo. Note that the b1SetColor method referenced here is in a code-behind file.

<StackPanel
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="SDKSample.EventOvw2"
  Name="dpanel2"
  Initialized="PrimeHandledToo"
>
  <StackPanel.Resources>
    <Style TargetType="{x:Type Button}">
      <EventSetter Event="Click" Handler="b1SetColor"/>
    </Style>
  </StackPanel.Resources>
  <Button>Click me</Button>
  <Button Name="ThisButton" Click="HandleThis">
    Raise event, handle it, use handled=true handler to get it anyway.
  </Button>
</StackPanel>

The advantage gained here is that the style is likely to contain a great deal of other information that could apply to any button in your application, and having the EventSetter be part of that style promotes code reuse even at the markup level. Also, an EventSetter abstracts method names for handlers one step further away from the general application and page markup.

Another specialized syntax that combines the routed event and animation features of WPF is an EventTrigger. Como com EventSetter, somente os eventos roteados que podem ser usados para um EventTrigger. Normalmente, um EventTrigger é declarada como parte de um estilo, mas uma EventTrigger também pode ser declarado em elementos de nível de página como parte do Triggers coleção, ou em um ControlTemplate. Um EventTrigger permite que você especifique um Storyboard que é executado sempre que um evento roteado atinge um elemento em sua rota que declara um EventTrigger para o evento. A vantagem de um EventTrigger simplesmente manipulando o evento e fazendo com que ele iniciar um storyboard existente é que uma EventTrigger proporciona maior controle sobre o storyboard e seu comportamento de tempo de execução. Para obter mais informações, consulte Como: Usar acionadores de eventos para controlar um Storyboard após seu início.

More About Routed Events

This topic mainly discusses routed events from the perspective of describing the basic concepts and offering guidance on how and when to respond to the routed events that are already present in the various base elements and controls. However, you can create your own routed event on your custom class along with all the necessary support, such as specialized event data classes and delegates. The routed event owner can be any class, but routed events must be raised by and handled by UIElement or ContentElement derived classes in order to be useful. For more information about custom events, see Como: Criar um evento roteado personalizado.

Consulte também

Referência

EventManager

RoutedEvent

RoutedEventArgs

Conceitos

Marcando Eventos Roteados como Manipulados e Manipulação de Classes

Input Overview

Visão geral de Comando

Propriedades de Dependência Personalizada

Árvores em WPF

Padrões de evento fraca