3

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.");
    }
}
Bob.
  • 3,894
  • 4
  • 44
  • 76
  • What do you mean by a class you don't have direct access to? – lc. Sep 05 '12 at 18:18
  • @lc.: Probably that he does not have a reference to an instance of class B in class A, but they require some means of communication. This happens a lot in MVVM type UI's. There is a way to deal with it via weak event references (static events are a bit evil because they cause havoc in the GC) – Ed S. Sep 05 '12 at 18:20
  • @lc. I mean, a class that isn't created inside the first, like in the above class where secondWindow is created inside MainWindow. I'd like to be able to point to the event as a separate property. – Bob. Sep 05 '12 at 18:21

1 Answers1

4

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).

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • Do you have any examples you can share? I'm trying to find a basic clean example that I can learn and debug with, without having all the complexity in it. – Bob. Sep 05 '12 at 19:19
  • Are there any simpler implementations of the Event Aggregator? Wrapping my head around all those different methods is rather complex. I found an [event aggregator library](http://eventaggregator.codeplex.com/) on Codeplex, where I just have to specify the ID and the method I want to use, but it doesn't exactly tell me how things are actually done. – Bob. Sep 11 '12 at 15:18