2
votes

How do you pass complex types to constructors, with the MVVM pattern and IoC? And how would you navigate to the new view?

Below is a simplified model which shows what I want to do.

class Weekday {
   List<Grocery> groceries;
}

class Grocery {
   string name;
}

class WeekdaysVm {
   List<Weekday> weekdays;

   public WeekdaysVm(IService service) { ... } 
}

class GroceriesVm {
   public GroceriesVm(IService service, List<Grocery> groceries) {
      ...
   }
   List<Grocery> groceries;
}

Say I am in the WeekdaysView and press a weekday. Now I want to navigate to the GroceryView with the weekday.Groceries passed to the GroceriesVm. How would I do this with MVVM and IoC?

Please imagine the setting being vastly more complex, with ~20 views navigating all over the place.

1

1 Answers

3
votes

MVVM doesnt include the concept of navigation, so what your asking is how would you navigate between views without violating the principles of MVVM within your views and viewmodels.

In my opinion you should create a class called INavigationFactory (for example) that can be injected into each ViewModel. Then on the interface you could expose Actions for the different navigations you want to make

Action GetPage1NavigationAction();
Action GetPage2NavigationAction();
Action GetPage3NavigationAction();

An example of the implementation of one of these methods might be:

public Action GetPage2NavigationAction()
{
   var action = () => 
   {
      var vm = new Page2ViewModel();
      var view = new Page2Page();
      view.DataCntext = vm;
      Navigate(view); // or whatever method you'd call to navigate
   }
   return action;
}

Then in your Page1 ViewModel (for instance), in your Button click command you can just have:

Avtion nextPageNav = navigationFactory.GetPage2NavigationAction();
nextPageNav();

You can include parameters in your factory actions to pass data between pages.