|
It's been a while since i posted anything on Prism. When I left p&p, i said you would see more posts on Prism on my blog. I've been pretty immersed in MEF since leaving and haven't done any posts on Prism yet. Today, I got inspired (albeit late in the evening) based on a post on the forums to actually do that, so here I am :-). The post was from TSChaena about using EventAggregator to fire generic events similar to the way we did things with EventBroker in CAB. Using EventBroker allows you to dynamically define events in your application that are identified through a topic name rather than needing to define a strongly typed class as you do with the EventAggregator. There are several advantages to not using the approach in EB which I have identified in this post . However, there are times when you want to do a dynamic eventing system. The good news is that there actually is a solution for doing this with our EventAggreator though it is not exactly the same as the way we did it in EB. CompositeWPFEvent Before we look at the solution I came up with, lets talk quickly about CompositeWPFEvent. CompositeWPFEvent is a generic class that contains one type parameter TPayload. TPayload defines the payload that will be passed into the event when it is fired. The subscriber also uses the payload to provide filters for the subscription. For example if TPayload is a FundOrder as in the EventAggregator QuickStart, then you can supply a lambda such as fundOrder=>fundOrder.CustomeriD == customerID for example to filter on only events that are received for a specific customer. The common pattern you will see for defining such events is to create a class that inherits from CompositeWPFEvent for each event that is typed to the specific paramers. For example below is the definition for the FundOrderAdded event. public class FundOrderAdded : CompositeWpfEvent<FundOrderAdded> {} This event is then retrieved from the EventAggregator by calling the GetEvent method passing FundOrderAdded as the event. Now, although this is the common pattern, there is nothing about the EventAggregator that requires you to create a new event class for each event. CompositeWPFEvent is not an abstract class, so you can simply "use" it as you will, even in a generic case. For example you can do the following. 1: public class ThrowsEvents { 2: public ThrowsEvents(IEventAggregator eventAgg) { 3: eventAgg.GetEvent<CompositeWPFEvent< string >>().Publish( "SomethingEvent" ) 4: eventAgg.GetEvent<CompositeWPFEvent< string >>().Publish( "SomethingElseEvent" ) 5: } 6: } 7: 8: public class HandlesEvents { 9: public HandlesEvents(IEventAggregator eventAgg) { 10: CompositeWPFEvent genericEvent = eventAgg.GetEvent<CompositeWPFEvent< string >>(); 11: genericEvent.Subscribe(action=>Console.WriteLine( "SomethingEvent fired" , ThreadOption.UIThread, 12: false , e=>e == "SomethingEvent" ); 13: genericEvent...
|