Prism: One View with multiple View Models

Jan 22, 2013 at 3:24 PM

I use prism with MEF and i have data comming from different modules can be displayed in a typical view because it is only list of items with search box to find certain item, so i need to have one view but be able to switch view models instead of building one view for each view model.

Jan 22, 2013 at 6:08 PM


Based on my understanding, if you want to define only one view for your different view models, then I believe a possible approach could be to export this view through an interface (e.g. ISearchView) defined in a common project. For example, this interface could define a property for the view model which should also respond to a common interface (e.g. ISearchViewModel), in order to establish a compatibility between the different view models and the common view. For example you could have the following property:

public ISearchViewModel ViewModel;
Then, in your modules you could define the logic to resolve the common view through this interface and also set its ViewModel property with the view model provided in this module to handle the search operation. And then once you have the resulting view with its corresponding view, for example you could inject the this view in a region. Take into that if you follow this approach, the view should be exported also using the following attribute:

As by default MEF will register the class as a singleton instance, which may not be necessary for this particular approach. Also, take into account that this may not be the only aproach to achieve this as this will deppend mostly on your personal preferences and the requirements of your scenario.

Please let us know if we have misunderstood your scenario,

Agustin Adami

Jan 22, 2013 at 7:01 PM

Hi aadami, thanks in advance, your answer exactly to the point, only one point remaining: if i put Radio button or Combo box in the Shell  window (which is laying in another project ) and upon the user selection in this control the required view model will be determined and consequently the view will be loaded to the region

i think the code to handle user selection will be exist in ShellWindow View Model then it will publish the selected option via EventAggregator for which the interested modules will subscribe and load the view to the region. is this approach right or wrong or there is better approach.

Jan 22, 2013 at 7:24 PM

I'm glad you find this useful, on the other hand, handling the user selection in the ShellWindow's view model and publishing this option through the EventAggregator seems like a reasonable approach to me.

Best Regards,

Agustin Adami