Thursday, October 13, 2011

Using the EventAggregator

The EventAggregator is the pattern that may be used in multiple scenarios, but in my case I have a WPF application that uses several User Control. When an action happens in a particular User Control (i.e. a user clicks the button), another User Controls or several User Controls react (i.e. draw an image). At first it looked like Routed Events and Commands are the way to go but I found out that could not easily build a working prototype so I decided to learn them at a later stage.

I found the explanation and a sample implementation here:

Simple message-based Event Aggregator

My prototype included two user controls, and I used the implementation of IEventAggregator and ISubscription from the link above.

That's the solution structure:

The user control that publishes the event does it in the following way:

public partial class DimensionsView : UserControl
{
private EventAggregator _eventAggregator = null;

private EventAggregator EventAggregator
{
get
{
if (_eventAggregator == null)
{
_eventAggregator = new EventAggregator();
}
return _eventAggregator;
}
}

public DimensionsView()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
//publish a message that will be subscribed to in another user control
EventAggregatorInstance.EAggregator.Publish(new BasicMessage("test"));
}

And the subscribing user control declares an action it's interested in explicitly and subscribes to it.

public partial class GridView : UserControl
{
private Action someAction;

private EventAggregator _eventAggregator = null;

private EventAggregator EvengAggregator
{
get
{
if (_eventAggregator == null)
{
_eventAggregator = new EventAggregator();
}
return _eventAggregator;
}
}

public GridView()
{
InitializeComponent();
someAction = message => Test(message);
var subscription = EventAggregatorInstance.singletonAggregator.Subscribe(someAction);
}

private void Test(BasicMessage msg)
{
PerformAction();
}

public void PerformAction()
{
System.Windows.Forms.MessageBox.Show("Action Performed");
}
}

That's pretty much all that's required to build a working prototype. Of course, an instance of the EventAggregator has to be created for the application to work. This can be done in multiple ways, I chose one of the simplest - a singleton.

public static class EventAggregatorInstance
{
public static EventAggregator EAggregator = null;

public static EventAggregator singletonAggregator
{
get
{
if (EAggregator == null)
{
EAggregator = new EventAggregator();
}
return EAggregator;
}
}
}

I haven't given up on the Routed Events and Commands, that's my next subject to explore!

by . Also posted on my website

No comments: