Forum Xamarin Xamarin.Forms

Navigating and passing parameter to a TabbedPage child view's ViewModel in MVVM

ReedReed Member ✭✭

What would be MVVM way of passing a parameter to the initial View's ViewModel, which is loaded into the detail area when navigating to the TabbedPage?

An example use case could be that I'm located in orders view, and click on one of the orders, it navigates me to the tabbed page that has order details view as the first tab. How do I pass the order details to the OrderDetailsViewModel? When using TabbedPage I have an additional layer in between. In my mind, the order details would have to be passed in a similar flow to this: OrdersViewModel ->TabbedPageViewModel -> OrderDetailsViewModel.

Is something like MessagingCenter viable solution for this type of communication?

I don't use MVVM Framework, but I wonder how would a frameworks like MvvmCross, Prism, MVVM Light would handle this scenario?


Best Answer


  • ReedReed Member ✭✭
    edited January 2019

    Thanks for the answer :)

    But what if my OrderDetailsViewModel has some services, that needs to be injected?

    Should I resolve the dependencies in MyTabbedPageViewModel?

    Or when I'm navigating to MyTabbedPageViewModel from OrdersViewModel, the OrdersViewModel should get the services through constructor injection and pass it down to MyTabbedPageViewModel constructor, which it will again forward to OrderDetailsViewModel constructor?

    It would be perfect if I could use InitializeAsync method that comes from ViewModelBase to pass the orderID instead of using the constructor. I use this book as a reference for my architecture:

  • LandLuLandLu Member, Xamarin Team Xamurai

    But what if my OrderDetailsViewModel has some services, that needs to be injected?

    You can expand my sample constructor to inject other services you want to use:

    public MyTabbedPageViewModel(string orderID, IOrderService orderService, other services...)
        _orderService = orderService;
        OrderDetailsViewTab = new OrderDetailsViewModel();
        // Do what you want here
        // Just pass the Id to OrderDetailsViewModel
        OrderDetailsViewTab.OrderID = orderID;

    You can also record this ID via a private proerty of MyTabbedPageViewModel, then you can pass this id to OrderDetailsViewModel when you want to do that instead of setting it to OrderDetailsViewTab directly.

Sign In or Register to comment.