Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to subscribe to an event indirectly?

Currently, I have this implemented, where I have direct access to the class that I want to subscribe to, but what happens if I have a class that I don't have direct access to? i.e. An event that X triggers, with Y subscribing to it. Is it possible to do such without using a static event? Like if you have two windows and one thing happens on one, and you want something to trigger off of it on the second window.

Example:

Y (listens for event and DoSomething()) ---.
                                           |----Event
X (triggers event when something changes) -'

Current code:

public static class MyEvents {
    public delegate void FirstEventHandler();
}

public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();

        SecondaryWindow secondWindow = new SecondaryWindow();
        secondWindow.Show();

        secondWindow.secondaryWindowEvent += new MyEvents.FirstEventHandler(callEvent);
    }

    protected void callEvent() {
        MessageBox.Show("This is a MessageBox.");
    }
}
like image 346
Bob. Avatar asked Dec 06 '25 01:12

Bob.


1 Answers

So, I had to deal with this in a WPF UI I worked on shortly. Having different parts of the UI separated is nice for many reasons, but in real applications they often need to communicate with one another, and passing around references is sub-optimal.

I used the Event Aggregator class in my app. It allows for logically separated components to remain loosely couple, but still able to communicate with one another via events . This approach saves you the headaches that are associated with static events (static events must be unsubscribed to before an object goes out of scope, else said object will not be eligible for garbage collection).

like image 90
Ed S. Avatar answered Dec 08 '25 14:12

Ed S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!