0

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");
    }
;
Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29
A191919
  • 3,422
  • 7
  • 49
  • 93
  • Check what is sent in `object o`. It could be either `PlotModel` or `CFDBOX` – Dmitry Bychenko Nov 18 '15 at 15:24
  • Do you have a way to identify the `CFDBOX` from a given `Axis`? You've got two options, you can find a way to do that, and in your handler, get it, or call `AxisChanged` from the `CFDBOX` itself (instead of from `CFDBOX.PlotModel.Axes[0]`) and then find which axis has changed some other way. – DrewJordan Nov 18 '15 at 15:41

2 Answers2

1

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;
}
Community
  • 1
  • 1
Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29
0

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.

BendEg
  • 20,098
  • 17
  • 57
  • 131