Procedura: gestire più eventi mediante le relative proprietàHow to: Handle Multiple Events Using Event Properties

Per utilizzare le proprietà evento è necessario definire queste proprietà nella classe tramite cui vengono generati gli eventi e, successivamente, impostarne i delegati nelle classi mediante cui vengono gestiti gli eventi.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. Per implementare più proprietà evento in una classe, la classe deve archiviare e mantenere internamente il delegato definito per ogni evento.To implement multiple event properties in a class, the class must internally store and maintain the delegate defined for each event. Uno degli approcci più comuni consiste nell'implementare una raccolta di delegati indicizzata da una chiave evento.A typical approach is to implement a delegate collection that is indexed by an event key.

Per archiviare i delegati per ogni evento, è possibile usare la classe EventHandlerList o implementare una raccolta personalizzata.To store the delegates for each event, you can use the EventHandlerList class, or implement your own collection. La classe della raccolta deve fornire metodi per l'impostazione, l'accesso e il recupero del delegato del gestore eventi in base alla chiave evento.The collection class must provide methods for setting, accessing, and retrieving the event handler delegate based on the event key. È possibile, ad esempio, usare una classe Hashtable o derivare una classe personalizzata dalla classe DictionaryBase.For example, you could use a Hashtable class, or derive a custom class from the DictionaryBase class. I dettagli sull'implementazione della raccolta di delegati non devono necessariamente essere esposti al di fuori della classe.The implementation details of the delegate collection do not need to be exposed outside your class.

Ogni proprietà evento all'interno della classe definisce un metodo della funzione di accesso add e un metodo della funzione di accesso remove.Each event property within the class defines an add accessor method and a remove accessor method. La funzione di accesso add di una proprietà evento aggiunge un'istanza del delegato di input alla raccolta di delegati.The add accessor for an event property adds the input delegate instance to the delegate collection. La funzione di accesso remove di una proprietà evento rimuove un'istanza del delegato di input dalla raccolta di delegati.The remove accessor for an event property removes the input delegate instance from the delegate collection. Le funzioni di accesso delle proprietà evento usano la chiave predefinita della proprietà per aggiungere e rimuovere istanze nella raccolta di delegati.The event property accessors use the predefined key for the event property to add and remove instances from the delegate collection.

Per gestire più eventi mediante le relative proprietàTo handle multiple events using event properties

  1. Definire una raccolta di delegati all'interno della classe che genera gli eventi.Define a delegate collection within the class that raises the events.

  2. Definire una chiave per ogni evento.Define a key for each event.

  3. Definire le proprietà evento nella classe che genera gli eventi.Define the event properties in the class that raises the events.

  4. Usare la raccolta di delegati per implementare i metodi delle funzioni di accesso add e remove per le proprietà evento.Use the delegate collection to implement the add and remove accessor methods for the event properties.

  5. Usare le proprietà evento pubbliche per aggiungere e rimuovere i delegati dei gestori eventi nelle classi che gestiscono gli eventi.Use the public event properties to add and remove event handler delegates in the classes that handle the events.

EsempioExample

L'esempio C# seguente implementa le proprietà evento MouseDown e MouseUp, usando un oggetto EventHandlerList per archiviare il delegato di ogni evento.The following C# example implements the event properties MouseDown and MouseUp, using an EventHandlerList to store each event's delegate. Le parole chiave dei costrutti delle proprietà evento sono riportate in grassetto.The keywords of the event property constructs are in bold type.

Nota

Le proprietà evento non sono supportate in Visual Basic 2005Visual Basic 2005.Event properties are not supported in Visual Basic 2005Visual Basic 2005.

// 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

Vedere ancheSee Also

System.ComponentModel.EventHandlerList
EventiEvents
Events
Procedura: Dichiarare eventi personalizzati per proteggere la memoriaHow to: Declare Custom Events To Conserve Memory