c# - Unsubscribing from anonymous delegate event -
i'm having trouble figuring out way of unsubscribing anonymous delegate events found in pre-made helper file helps allow movement of controls @ run time. reason want unsubscribe these events control (in case buttons) become locked again , not able moved. here method in helper class:
public static void init(control control) { init(control, direction.any); } public static void init(control control, direction direction) { init(control, control, direction); } public static void init(control control, control container, direction direction) { bool dragging = false; point dragstart = point.empty; control.mousedown += delegate(object sender, mouseeventargs e) { dragging = true; dragstart = new point(e.x, e.y); control.capture = true; }; control.mouseup += delegate(object sender, mouseeventargs e) { dragging = false; control.capture = false; }; control.mousemove += delegate(object sender, mouseeventargs e) { if (dragging) { if (direction != direction.vertical) container.left = math.max(0, e.x + container.left - dragstart.x); if (direction != direction.horizontal) container.top = math.max(0, e.y + container.top - dragstart.y); } }; }
and here's how subscribe these events calling method;
controlmover.init(this.controls["btn" + i]);
i've read methods on msdn unsubscribing these creating local variable holding these events , unsubscribing through way, can't seem working in own project. how go unsubscribing these events controls become fixed in position again?
anonymous delegates not guaranteed unique created compiler, when unsubscribing lack of uniqueness of same code cause fail unsubscribe correct handler. way safely keep reference delegate , use unsubscribe, or change full method.
delegates equal based on object instance , method signature believe.
a possible duplicate:
how remove lambda event handler
basically, keep reference:
mouseeventhandler handler = (sender, e) => { dragging = true; dragstart = new point(e.x, e.y); control.capture = true; }; control.mousedown += handler; control.mousedown -= handler;
or turn anonymous method proper method.
Comments
Post a Comment