Notify when event from another class is triggered [duplicate]

ε祈祈猫儿з 提交于 2019-11-28 19:01:18

You'll need to declare a public event on class 'B' - and have class 'A' subscribe to it:

Something like this:

class B
{
    //A public event for listeners to subscribe to
    public event EventHandler SomethingHappened;

    private void Button_Click(object o, EventArgs s)
    {
        //Fire the event - notifying all subscribers
        if(SomethingHappened != null)
            SomethingHappened(this, null);
    }
....

class A
{
    //Where B is used - subscribe to it's public event
    public A()
    {
        B objectToSubscribeTo = new B();
        objectToSubscribeTo.SomethingHappened += HandleSomethingHappening;
    }

    public void HandleSomethingHappening(object sender, EventArgs e)
    {
        //Do something here
    }

....

You need three things (which is marked by comments in code):

  1. Declare event in class B
  2. Raise event in class B when something happened (in your case - Button_Click event handler executed). Keep in mind that you need to verify if there are any subscribers exists. Otherwise you will get NullReferenceException on raising event.
  3. Subscribe to event of class B. You need to have instance of class B, which even you want to subscribe (another option - static events, but those events will be raised by all instances of class B).

Code:

class A
{
    B b;

    public A(B b)
    {
        this.b = b;
        // subscribe to event
        b.SomethingHappened += MyMethod;
    }

    private void MyMethod() { }
}

class B
{
    // declare event
    public event Action SomethingHappened;

    private void Button_Click(object o, EventArgs s)
    {
         // raise event
         if (SomethingHappened != null)
             SomethingHappened();

         SomeMethod();
    }

    public void SomeMethod() { }
}

Have a look at rasing an event from Class B

Have a look at

Raising an Event

Handling and Raising Events

How to: Raise and Consume Events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!