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

后端 未结 3 1612
小鲜肉
小鲜肉 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条回答
  •  萌比男神i
    2021-01-15 08:47

    Step 1) Expose an event on MainForm... say..

    public event Action simpleEvent
    

    Step 2) Give MyUserControl a constructor that takes an instance of MainForm and bind an action to that event

    public MyUserControl(MainForm form) {
        form += () => Console.WriteLine("We're doing something!")
    }
    

    Step 3) raise the event in MainForm.Button_Click

    if(simpleEvent != null) simpleEvent();
    

    Note: You could register your own delegates and work with something other than lambda expressions. See http://msdn.microsoft.com/en-us/library/17sde2xt.aspx for a more thorough explanation

    Your end result would look like...

    public Class MainForm : Form
    {
        public event Action MyEvent;
    
        MyUserControl MyControl = new MyUserControl(this);
        private void Button_Click(object sender, EventArgs e)
        {
            if(simpleEvent != null) simpleEvent();
        }    
    }
    
    public Class MyUserControl : UserControl
    {
        //listen for MyEvent from MainForm, and perform MyMethod
        public MyUserControl(MainForm form) {
            simpleEvent += () => MyMethod();
        }
    
        public void MyMethod()
        {
             //Do Stuff here
        }
    }
    

提交回复
热议问题