Bhanu Vanka
Bhanu Vanka

Reputation: 31

How to pass INavigationService from parent ContentPage ViewModel to child ContentView ViewModel?

I am using Xamarin Forms and Prism. My navigation between pages is done using Prism INavigationService. I have a Xamarin Forms ContentPage with many child ContentViews which have their own View Models. When I click a child ContentView I would like to navigate to another ContentPage with some properties from child ContentView. I want to know if its possible to pass the parent view model INavigationService to child ContentView view model ? Or Is there any other best practices out there which can be used to suit my requirement ?

Upvotes: 0

Views: 465

Answers (2)

Bhanu Vanka
Bhanu Vanka

Reputation: 31

At the moment the only workaround working for me is I have disconnected auto wiring for child view models. And I have a created all my child view models as member variables in my content page view model and bind them to the views in the XAML. It is working for now. I am not sure this the best practice. If somebody find has a better solution please let me know.

Upvotes: 0

Ahmad ElMadi
Ahmad ElMadi

Reputation: 2617

What you need to do is to register the Page in your prismApplcation which is useually your App.xaml Once you register your page using RegisterForNavigation< Page> then you can inject the INavigationService in the page's Constructor like this

private INavigationService _navigationService;
public MyPage(INavigationService navigationService)
{
   _navigationService = navigationService 
}

Alternativly you can do the same thing (which is recommended) in the ViewModel of the page , but you need to make sure to turn on the Autolocater in the Xaml file of the page.

This is the case if you want to navigate between content pages. However, in your case you have multi views and each view has its own viewmodel, although that is kind of breaking the rules since the views can basically share the viewmodel from their page, but if you insist in having it this way, my only advice, without looking at your code, is to register the viewmodels for each view using the same container you registered the page with. Use RegisterType<>() for that and you will find that Inavigationservice will be injected. Once again I think it is better that you would change your code design.

Upvotes: 0

Related Questions