C#, How to create an event and listen for it in another class?

后端 未结 3 1630
小鲜肉
小鲜肉 2021-01-15 08:09

I can\'t figure out how to do this, heres sample code. Of what I wish to do.

public Class MainForm : Form
{
    MyUserControl MyControl = new MyUserControl;
         


        
3条回答
  •  一个人的身影
    2021-01-15 08:24

    //listen for MyEvent from MainForm, and perform MyMethod
    

    That's the wrong way around. Publishing an event in control is useful, the control cannot possibly guess how it is going to get used. It however most certainly should not know anything about an event that may or may not be available in the form that it gets dropped on. That has the nasty habit of blowing up when the form just doesn't (yet) have the event. The bad kind too, a crash at design time that puts up the White Screen of Darn and prevents you from fixing the problem.

    A form doesn't have to guess, it knows exactly what controls it has. So where ever in the form you might want to raise the event, just call the control's MyMethod method directly. And if that's wrong for some reason, like removing the control but not the call, then you just get a compile error that's easy to fix.

提交回复
热议问题