Como manipular vários eventos usando propriedades de eventoHow to: Handle Multiple Events Using Event Properties

Para usar as propriedades de evento, defina as propriedades de evento na classe que gera os eventos e, em seguida, defina os representantes das propriedades de evento nas classes que tratam dos eventos.To use event properties, you define the event properties in the class that raises the events, and then set the delegates for the event properties in classes that handle the events. Para implementar várias propriedades de evento em uma classe, a classe deve armazenar e manter internamente o representante definido para cada evento.To implement multiple event properties in a class, the class must internally store and maintain the delegate defined for each event. Uma abordagem típica é implementar uma coleção de representantes indexada por uma chave de evento.A typical approach is to implement a delegate collection that is indexed by an event key.

Para armazenar os representantes para cada evento, você pode usar a classe EventHandlerList ou implementar sua própria coleção.To store the delegates for each event, you can use the EventHandlerList class, or implement your own collection. A classe da coleção deve fornecer métodos para configurar, acessar e recuperar o representante do manipulador de eventos com base na chave de evento.The collection class must provide methods for setting, accessing, and retrieving the event handler delegate based on the event key. Por exemplo, você poderia usar uma classe Hashtable ou derivar uma classe personalizada da classe DictionaryBase.For example, you could use a Hashtable class, or derive a custom class from the DictionaryBase class. Os detalhes da implementação da coleção de representantes não precisam ser expostos fora de sua classe.The implementation details of the delegate collection do not need to be exposed outside your class.

Cada propriedade de evento dentro da classe define um método adicionar acessador e um método remover acessador.Each event property within the class defines an add accessor method and a remove accessor method. O método adicionar acessador de uma propriedade de eventos adiciona a instância do representante de entrada à coleção de representantes.The add accessor for an event property adds the input delegate instance to the delegate collection. O acessador de remoção de uma propriedade de evento remove a instância do representante de entrada da coleção de representantes.The remove accessor for an event property removes the input delegate instance from the delegate collection. Os acessadores de propriedades de evento usam a chave predefinida na propriedade de evento para adicionar e remover instâncias da coleção de representantes.The event property accessors use the predefined key for the event property to add and remove instances from the delegate collection.

Para manipular vários eventos usando propriedades de eventoTo handle multiple events using event properties

  1. Defina a coleção de representantes na classe que gera os eventos.Define a delegate collection within the class that raises the events.

  2. Defina uma chave para cada evento.Define a key for each event.

  3. Defina as propriedades de evento na classe que gera os eventos.Define the event properties in the class that raises the events.

  4. Use a coleção de representantes para implementar os métodos adicionar e remover acessador nas propriedades de evento.Use the delegate collection to implement the add and remove accessor methods for the event properties.

  5. Use as propriedades de evento públicas para adicionar e remover representantes do manipulador de eventos nas classes que tratam dos eventos.Use the public event properties to add and remove event handler delegates in the classes that handle the events.

ExemploExample

O exemplo de C# a seguir implementa as propriedades de evento MouseDown e MouseUp usando uma EventHandlerList para armazenar o representante de cada evento.The following C# example implements the event properties MouseDown and MouseUp, using an EventHandlerList to store each event's delegate. As palavras-chave dos constructos de propriedade de evento estão em negrito.The keywords of the event property constructs are in bold type.

// The class SampleControl defines two event properties, MouseUp and MouseDown.
ref class SampleControl : Component
{
    // :
    // Define other control methods and properties.
    // :

    // Define the delegate collection.
protected:
    EventHandlerList^ listEventDelegates;

private:
    // Define a unique key for each event.
    static Object^ mouseDownEventKey = gcnew Object();
    static Object^ mouseUpEventKey = gcnew Object();

    // Define the MouseDown event property.
public:
    SampleControl()
    {
        listEventDelegates = gcnew EventHandlerList();
    }

    event MouseEventHandler^ MouseDown
    {
        // Add the input delegate to the collection.
        void add(MouseEventHandler^ value)
        {
            listEventDelegates->AddHandler(mouseDownEventKey, value);
        }
        // Remove the input delegate from the collection.
        void remove(MouseEventHandler^ value)
        {
            listEventDelegates->RemoveHandler(mouseDownEventKey, value);
        }
        // Raise the event with the delegate specified by mouseDownEventKey
        void raise(Object^ sender, MouseEventArgs^ e)
        {
            MouseEventHandler^ mouseEventDelegate =
                (MouseEventHandler^)listEventDelegates[mouseDownEventKey];
            mouseEventDelegate(sender, e);
        }
    }

    // Define the MouseUp event property.
    event MouseEventHandler^ MouseUp
    {
        // Add the input delegate to the collection.
        void add(MouseEventHandler^ value)
        {
            listEventDelegates->AddHandler(mouseUpEventKey, value);
        }
        // Remove the input delegate from the collection.
        void remove(MouseEventHandler^ value)
        {
            listEventDelegates->RemoveHandler(mouseUpEventKey, value);
        }
        // Raise the event with the delegate specified by mouseUpEventKey
        void raise(Object^ sender, MouseEventArgs^ e)
        {
            MouseEventHandler^ mouseEventDelegate =
                (MouseEventHandler^)listEventDelegates[mouseUpEventKey];
            mouseEventDelegate(sender, e);
        }
    }
};
// The class SampleControl defines two event properties, MouseUp and MouseDown.
class SampleControl : Component
{
    // :
    // Define other control methods and properties.
    // :

    // Define the delegate collection.
    protected EventHandlerList listEventDelegates = new EventHandlerList();

    // Define a unique key for each event.
    static readonly object mouseDownEventKey = new object();
    static readonly object mouseUpEventKey = new object();

    // Define the MouseDown event property.
    public event MouseEventHandler MouseDown
    {
        // Add the input delegate to the collection.
        add
        {
            listEventDelegates.AddHandler(mouseDownEventKey, value);
        }
        // Remove the input delegate from the collection.
        remove
        {
            listEventDelegates.RemoveHandler(mouseDownEventKey, value);
        }
    }

    // Raise the event with the delegate specified by mouseDownEventKey
    private void OnMouseDown(MouseEventArgs e)
    {
        MouseEventHandler mouseEventDelegate =
            (MouseEventHandler)listEventDelegates[mouseDownEventKey];
        mouseEventDelegate(this, e);
    }

    // Define the MouseUp event property.
    public event MouseEventHandler MouseUp
    {
        // Add the input delegate to the collection.
        add
        {
            listEventDelegates.AddHandler(mouseUpEventKey, value);
        }
        // Remove the input delegate from the collection.
        remove
        {
            listEventDelegates.RemoveHandler(mouseUpEventKey, value);
        }
    }

    // Raise the event with the delegate specified by mouseUpEventKey
    private void OnMouseUp(MouseEventArgs e)
    {
        MouseEventHandler mouseEventDelegate =
            (MouseEventHandler)listEventDelegates[mouseUpEventKey];
        mouseEventDelegate(this, e);
    }
}
' The class SampleControl defines two event properties, MouseUp and MouseDown.
Class SampleControl
    Inherits Component
    ' :
    ' Define other control methods and properties.
    ' :

    ' Define the delegate collection.
    Protected listEventDelegates As New EventHandlerList()

    ' Define a unique key for each event.
    Shared ReadOnly mouseDownEventKey As New Object()
    Shared ReadOnly mouseUpEventKey As New Object()

    ' Define the MouseDown event property.
    Public Custom Event MouseDown As MouseEventHandler
        ' Add the input delegate to the collection.
        AddHandler(Value As MouseEventHandler)
            listEventDelegates.AddHandler(mouseDownEventKey, Value)
        End AddHandler
        ' Remove the input delegate from the collection.
        RemoveHandler(Value As MouseEventHandler)
            listEventDelegates.RemoveHandler(mouseDownEventKey, Value)
        End RemoveHandler
        ' Raise the event with the delegate specified by mouseDownEventKey
        RaiseEvent(sender As Object, e As MouseEventArgs)
            Dim mouseEventDelegate As MouseEventHandler = _
                listEventDelegates(mouseDownEventKey)
            mouseEventDelegate(sender, e)
        End RaiseEvent
    End Event

    ' Define the MouseUp event property.
    Public Custom Event MouseUp As MouseEventHandler
        ' Add the input delegate to the collection.
        AddHandler(Value As MouseEventHandler)
            listEventDelegates.AddHandler(mouseUpEventKey, Value)
        End AddHandler
        ' Remove the input delegate from the collection.
        RemoveHandler(Value As MouseEventHandler)
            listEventDelegates.RemoveHandler(mouseUpEventKey, Value)
        End RemoveHandler
        ' Raise the event with the delegate specified by mouseDownUpKey
        RaiseEvent(sender As Object, e As MouseEventArgs)
            Dim mouseEventDelegate As MouseEventHandler = _
                listEventDelegates(mouseUpEventKey)
            mouseEventDelegate(sender, e)
        End RaiseEvent
    End Event
End Class

Consulte tambémSee also