EventAggregator Pattern: How To Pass Data?
I am looking at utilizing the Event Aggregator Pattern on a UI project I am working on (Silverlight/MVVM) to support loose coupling between views/viewmodels. We have written a few screens using a simple eventing system--it's not much more than a proof of concept at this point, but it does seem like a very elegent solution to creating a loosely coupled system.
The problem I am running up against is passing data from one ViewModel to another when the receiving ViewModel is not instantiated yet. For example, if a Customer List开发者_如何学运维 screen is open, a user might click a specific customer to open an edit/view Customer Detail screen (perhaps in a child window). The Customer Detail screen needs a customer (or customer Id) in order to function.
So is seems reasonable that the OpenCustomerDetailEvent would contain the relevant customer information, but what are some options for injecting that information into the Customer Detail V/VM? Since it's not in memory yet when the event is handled, it can't directly listen for the event (it can't itself be the handler). We are using a depenency injection container to create both the view and view model (we currently do "view first"), so having a separate handler inject the data via the constructor is not a great option.
What are some other options for getting the data into the View(Model) once it's constructed? An init method that takes strongly typed parameters? Using a setter to inject the data? Having the handler create the V/VM and then dispatch a second event that the VM listens for?
For this purpose i´m using the Prism Framework in my silverlight application. It provides an implementation of the EventAggregator pattern and a view navigation infrastructure.
In the case of prism, you will use NavigationParameters, that provide information for a view/viewmodel what data to use and to initialize. If the view/viewmodel isn´t created yet, the EventAggregator pattern is useless, cause it isn´t registered to the event yet.
If you want to rely on your own framework, i would take a look at the prism framework how view navigation is implemented there and to pick up some pieces for your own framework.
Personally i would encourage you, to use the prism framework.
精彩评论