2
votes

I'm learning prism V4 using MEF to load my modules. Loading modules does work, but in one module I want to load a View/ViewModel (MVVM) and don't really know how I get MEF to resolve all this stuff for me.

First: how do I need to mark the ViewModel (I follow the StockTraderRI example) so it is not loaded on startup but instead can be loaded during runtime into a region?

Second: how do I load the ViewModel using MEF so it gets connected to the corresponding interfaces?

MEF does this very nicely for things on startup which are marked as [Export], but I got no idea how to achieve this during runtime.

1

1 Answers

2
votes

You can use what is known as a Lazy Export so that the interface is not resolved until you explicitly use it.


If you need to create multiple instances, MEF doesn't support this particularly well. You can either do your own discovery and instantiation, or you can define the Export like this:

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(ISomething)]
public class Something : ISomething { }

The downside is that now wherever you need to create the instance, you need to have a reference to the actual Container instance. Then you can do:

var something = _container.GetExportedObject<ISomething>();

EDIT: Okay, I think I understand better what you're after. Here is how I've typically resolved this issue:

  1. I implement my View objects as UserControl instances and don't set a DataContext anywhere in their code or XAML.

  2. I create a DataTemplate that binds from the Type of the ViewModel to the UserControl.

  3. On my MainViewModel (or whatever corresponds to the View hosting the regions), I expose a general RegionX Object (possibly typed to an interface if all of my ViewModels will share some common functionality, but Object works fine).

  4. I create a ContentPresenter with Content bound to the RegionX property.

  5. Now my MainViewModel can import different ViewModel instances corresponding to the types of ViewModels that might be hosted by the RegionX. When I want to switch the 'active' View in the region, I simply set RegionX to the corresponding ViewModel.