Wednesday, September 14, 2011

Event Aggregator in Prism 4.0 with MEF

Today I am going to share a simple trick about Event Aggregator, I was working in one of my project and I was trying to use event aggregator. I was stopped by a show stopper exception, and couldn’t find out what is going on. here is the expectation that I had.

image

Looks familiar? I bet some of you had encounter it. well the solution is pretty easy while subscribing an event you got to also set your thread option and off course a true value to keep reference alive parameter of the subscribe method.

public InboxViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
var myDemoEvent = _eventAggregator.GetEvent<MyDemoEvent>();
if (myDemoEvent != null)
myDemoEvent.Subscribe(OnEvent,ThreadOption.UIThread,true);
}
private void OnEvent(MyCustomObject obj)
{
//do some thing over here
}



I already assume that you know about how to make a custom event for Event aggregator. If not here is a code sample. The main catch is that it have to be inherited from CompositePresentationEvent<>. The code sample is given bellow.

 public class MyDemoEvent:CompositePresentationEvent<MyCustomObject>
{
//here goes thing about your cutom event
}

public class MyCustomObject
{
//here goes you custom event payload stuff
}



Till next post happy programming.

No comments:

Post a Comment