You can do the following. You can create your child view model using a regular constructor, and then call ComposeParts on the instance to add everything:
var patientViewModel = new PatientViewModel(patient); _container.ComposeParts(patientViewModel);
But doing it every time is not very good for a number of reasons. To solve this scenario and encapsulate the use of MEF, I created a helper service for creating view models. It is called IViewModelFactory , and here is what it looks like:
[Export(typeof(IViewModelFactory))] [PartCreationPolicy(CreationPolicy.Shared)] internal class ViewModelFactory : IViewModelFactory { [ImportingConstructor] public ViewModelFactory(CompositionContainer container) { Contract.Requires(container != null); Container = container; } protected CompositionContainer Container { get; private set; } public T Create<T>(params object[] args) where T : class { T result; try { bool populateDependencies = false; if (args == null || args.Length == 0) {
Using this factory, you can create child-view models as follows:
var patientViewModel = ViewModelFactory.Create<PatientViewModel>(patient);
The disadvantage is that when using constructor parameters, you lose compilation time checking for parameter types, quantity, order, etc.
source share