3

Possible Duplicate:
Unsubscribe anonymous method in C#

I have some Panels that when created they are delegated to become clickable:

int z2 = z;
PicBx[z].Click += delegate { clicked(z2, null); };

I want to be able to remove this if the program calls for it. I tried using:

int z2 = z;
PicBx[z].Click -= delegate { clicked(z2, null); };

But it didn't work. Is there any way to remove the clickable delegation from it?

Community
  • 1
  • 1
user770344
  • 473
  • 2
  • 8
  • 16

1 Answers1

11

You can't unsubscribe from anonymous delegate, you need to keep reference to delegate

var myClickDelegate = (RoutedEventHandler)delegate { clicked(z2, null); };

PicBx[z].Click += myClickDelegate;

...

PicBx[z].Click -= myClickDelegate;

Or create named function

Hope this helps

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
  • Im getting "Cannot assign anonymous method to an implicitly-typed local variable" when using `var myClickDelegate = delegate { clicked(z2, null); };` – user770344 Aug 09 '11 at 21:23
  • try edited post, add (RoutedEventHandler) type converter – Arsen Mkrtchyan Aug 09 '11 at 21:26
  • This didn't work. On the program you can select a panel and remove it which changes the order. For some reason its keeping the delegation order of the panels after removal. Right now I'm just trying to remove all the delegation from all the panels after removal of one, to test for now. – user770344 Aug 10 '11 at 00:43
  • I just test it in a simple application, it works fine, check you business – Arsen Mkrtchyan Aug 10 '11 at 17:45