Search code examples
exportmef

MEF, how to get views using the container?


I'm using MEF to organize and create views using ViewExports like These:

[ViewExport(RegionName = "CustTabs")]
[ViewSortHint("20")]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class SomeLocalView : UserControl

Creating Views and ViewModels using These does work nicely. Now for one occasion I need all views exported with a special RegionName. For other exports (and contract names instead of region names) I would use

container.GetExportedValues<SomeType>("CustTabs");

to get/create all views with this region/contract. But this does not work for things exported using ViewExport.

So how do I get/create classes exported using the ViewExport attribute from the container?


Solution

  • The ViewExport attribute automatically registers all views that it's attached to as UserControls in the container. From memory, I think you can get a list of them with

    container.GetExportedValues<Lazy<UserControl,IViewRegionRegistration>>;
    

    Inspecting the metadata will tell you which region they're registered to.

    The only other way I can think of that may be a bit cleaner is to add an additional Export attribute to export the view as the desired type.