[FIXED] Ioc, DI and passing the data between pages in Xamarin Forms

Issue

Following this documentation, I am binding the viewmodel using ServiceProvider using following code:

this.BindingContext = App.Current.Services.GetService(typeof(ViewModelA));

But for business rules, I need to pass the data between pages and after doing research I came across this stackoverflow question and it is suggested to use following code

this.BindingContext = new ViewModelA(data);

So I am not sure if this breaks mvvm pattern or not. If it breaks then is there any another way of passing the data while using Ioc & DI. Any help would be appreciated.

Solution

Jason’s suggestion was easiest to implement. I created Init(data) in the BaseViewModel which is then inherited by other viewmodels. And I bind the viewmodels using ServiceProvider.

var viewModelA = App.Current.Services.GetService<ViewModelA>();
viewModelA.Init(data);
this.BindingContext = viewModelA;

Answered By – Harsh

Answer Checked By – Senaida (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published