0

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.

Harsh
  • 115
  • 2
  • 6
  • 1
    why not just add an `Init(data)` method that you can use to pass the `data` instead of using the constructor? – Jason Aug 22 '22 at 16:29
  • 'So I am not sure if this breaks mvvm pattern or not'. MVVM is loosely defined and even more it is not prescriptive. It clearly says that it is completely OK to break it in some situations and that it is not a proper solution for all problems. So if you feel like that this works for you don't be bothered with the theory. – Ivan Ičin Aug 22 '22 at 23:24

2 Answers2

0

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>();

ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196
0

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;
Harsh
  • 115
  • 2
  • 6