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

后端 未结 3 1582
小鲜肉
小鲜肉 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:41

    This is how to delegate to an event of a private member, so the outside can listen to it.

    public event EventHandlerType EventHandlerName
    {
        add
        {
            this._privateControl.EventHandlerName += value;
        }
        remove
        {
            this._privateControl.EventHandlerName -= value;            
        }
    }
    

    Another option would be to have an event in your form class:

    public event EventHandler MyEvent;
    

    And listen to the private member's event:

    this._customControl.SomeEvent += this.SomeEventHandler;
    

    With this:

    private void SomeEventHandler(object sender, EventArgs e)
    {
        if (this.MyEvent != null)
        {
            this.MyEvent(this, e);
        }
    }
    

    The usage from the outside in both cases will be the same:

    var form = new Form1();
    
    form1.MyEvent += (o, e) => { Console.WriteLine("Event called!"); };
    

    The bottom line is the you must implement functionality inside your form to allow the outside subscribe/listen to inner events.

提交回复
热议问题