A191919
A191919

Reputation: 3442

Event pass parameter

I have problem with event. For example let i have event public event EventHandler<AxisChangedEventArgs> AxisChanged which fires when Axis pan or zoom or something else. When it's firing i am making Console.WriteLine("Working");. How can i pass CFDBOX parameter into SomeWork anonymous method does not help because it will be imposible to unsubscribe from it. And i cannot override AxisChanged event.

public void AddEvents(CFDBOX CFDBOX) {
    CFDBOX.PlotModel.Axes[0].AxisChanged += SomeWork;
}

public void RemoveEvents(CFDBOX CFDBOX) {
    CFDBOX.PlotModel.Axes[0].AxisChanged -= SomeWork;
}

public EventHandler<AxisChangedEventArgs> SomeWork =
    delegate(object o, AxisChangedEventArgs args) {
        Console.WriteLine("Working");
    }
;

Upvotes: 0

Views: 59

Answers (2)

Binkan Salaryman
Binkan Salaryman

Reputation: 3048

Take advantage of closure lambda expressions:

private EventHandler<AxisChangedEventArgs> axisChangedEventHandler;

public void AddEvent(CFDBOX CFDBOX) {
    // keep a reference of the event handler to remove it later
    axisChangedEventHandler = (o, args) => {
        // parameter CFDBOX bound to the event handler
        Console.WriteLine("Working " + CFDBOX); 
    };
    // register event handler
    CFDBOX.PlotModel.Axes[0].AxisChanged += axisChangedEventHandler;
}

public void RemoveEvent() {
    // unregister event handler
    CFDBOX.PlotModel.Axes[0].AxisChanged -= axisChangedEventHandler;
}

Upvotes: 1

BendEg
BendEg

Reputation: 21088

Any parameter which must be passed with an event should be a member of your EventArgs implementation. In your scenario: AxisChangedEventArgs. Hope i get your question.

The sender of the event (in your case o) should always be the instance, which calls the event. So if your event get's fired from different classes (not instances!), you will have to check for the type of o.

Upvotes: 0

Related Questions