简体   繁体   中英

Removing event handlers in c#

I'm working on a Windows Forms app and I've come to a point where I can't understand what's happening.

I have something similar to an MVC architecture. Sometimes I want controls that belong to the view to stop listening to events. So inside the view code I've written a method that looks like this:

public void enableEventHandlers(bool enable)
{
    if (enable)
    {
        control.someEvent += someEventHandler;
    }
    else
    {
        control.someEvent -= someEventHandler;
    }
}

The thing is: when I want to remove an event handler I just call this method with false as a parameter. If I call this method from inside the view code it works just fine. But if I call this method from inside the controller code, it doesn't work (the event handlers are not removed).

Just to give a little more context:

This works:

public partial class View : Form
{
     public void enableEventHandlers(bool enable)
     {
         // The code I already showed
     }

     public void doSomething()
     {
         enableEventHandlers(false);
         // do something
         enableEventHandlers(true);
     }
 }

This doens't work:

public class controller
{
     private View myView;

     public void doSomething()
     {
         myView.enableEventHandlers(false);
         // Do something... but somehow everything inside my Form is still paying attention to events
         myView.enableEventHandlers(true);
     }
}

Finally I found the problem. It seems that somehow I was attaching an event handler twice to the same Control. I couldn't find the exact line number where I was doing that anyway. The solution I found is to remove an event handler before adding a new one. So the method enableEventHandlers looks now like this:

public void enableEventHandlers(bool enable) {
    if (enable)
    {
        control.someEvent -= someEventHandler;
        control.someEvent += someEventHandler;
    }
    else
    {
        control.someEvent -= someEventHandler;
    } 
}

Thanks for your answers.

I don't know if that's it but you didn't initialize your View. You just say "private View view", but that doesn't point to anywhere. You want to either make a new View by doing private View v = new View(), or let that view point to the view that you want to change the events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM