Question

Here's the situation

I have 2 singleton classes (ViewModels in fact).

[Export]
[PartCreationPolicy(CreationPolicy.Shared)]
public class CompanyViewModel, INavigationAware
{
   private Model.Company _selected;

   [ImportingConstructor]
   public CompanyViewModel(Service.ICompany companyService)
   {
      Companies = companyService.Companies;       
   }

   [Export("SelectedCompany")]
   public Model.Company Selected
   {
      get
      {
         return _selected;
      }
      set
      {
         _selected = value;
      }
   }

   public ObservableCollection<Model.Company> Companies{get;set;}

   public void OnNavigatedTo(NavigationContext navigationContext)
   {
      _selected = Companies.First();
   }
   ~~~
}

The companyService returns with 2 companies "A" and "B". "A" is set as the selected company when the class CompanyViewModel is navigated to. The user then selects company "B" and CompanyViewModel is updated via it's binding.

[Export]
[PartCreationPolicy(CreationPolicy.Shared)]    
public class DepartmentViewModel, INavigationAware
{
   [Import("SelectedCompany")]
   private Model.Company _selectedCompany{get;set;};

   [ImportingConstructor]
   public DepartmentViewModel(Service.IDeparment departmentService)
   {
      Departments= departmentService.Departments;
   }

   public ObservableCollection<Model.Department> Departments{get;set;}

   public void OnNavigatedTo(NavigationContext navigationContext)
   {
      this.departmentService.Refresh(_selectedCompany);
   }
   ~~~
}

After the events described above the DepartmentViewModel is created. The problem is the company property in the DepartmentViewModel is set to company "A" not company "B" as I would of expected, as I thought MEF would import the last value Selected was set to (before creation of DepartmentViewModel) not the first value it was set to.

Can someone tell me what's actually going on?

Was it helpful?

Solution

I believe you use MEF not as it is designed. MEF is not for "bindings" as you try to use it. MEF is for creating composition applications.

In your case the problem is that MEF doesn't update part registration for SelectedCompany after creation of CompanyViewModel. This is why it returns A always.

Use another approach - create separate DepartmentViewModel for each Company, or update it accordingly to selected company. Don't use MEF for that - use MEF only as "container that initialize your application once, during its startup".

PS. Actually, I never saw before usage of Export attribute for properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top