Search code examples
xamarin.iosxamarinmvvmcross

Passing data in a pop/back event to a previous view model


I have a structure like so :

SessionsView -> CreateSessionView

with view models like so :

SessionsViewModel - List of Session objects

CreateSessionViewModel - Single Session Object

The user fills in a form in create session, populates the Session object on the view model, hits done and I call : NavigationController.PopViewControllerAnimated(true) to take them back to the list of sessions.

Is there a way of passing my newly created session object back to the previous views Viewmodel and adding it to its list of session objects? I know how to pass params in a ShowViewModel<TYPE>(PARAM) command, but not sure how to do it whilst navigating back.

Update 1 :

I found 'a' way to do it.. doesn't feel too nice though :

var sessionsView = (SessionsView)NavigationController.ViewControllers.FirstOrDefault(vc => vc is SessionsView);
                    var sessionsViewModel = (SessionsViewModel)sessionsView.ViewModel;
                    sessionsViewModel.Sessions.Add(vModel.Session);
                    NavigationController.PopViewControllerAnimated(true);

Solution

  • Just make use of the return parameter of PopViewControllerAnimated(bool animated).

    NavigationController.PopViewControllerAnimated(true);
    ViewControllerClass viewController = (ViewControllerClass)NavigationController.TopViewController;
    viewController.StoreSessionObject(session); <-- you need to create this method