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.
CodePudding user response:
Jason's suggestion is one way to solve this.
An alternative approach requires additional setup.
See Constructor injection.
Specifically, in ConfigureServices(), add
services.AddSingleton<MyData>();
,
where MyData
is the class for data
parameter declared in ViewModel's constructor.
OR if you use the recommended approach of declaring an Interface IMyData
, that you use everywhere instead of directly referring to class MyData
, do
services.AddSingleton<IMyData, MyData>();
CodePudding user response:
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;