MAUI navigation to new page with injected viewModel
If you think this belong more into #mobile channel I can move, but I think some of you who are more familiar with dependency injection might be able to understand/help.
In .net MAUI there is a dep.inj and I watched some tutorial where they injected ContentPage classes, as well as viewModels (and those have some injected stuff in constructors as well).
So currently I have something like this:
and my Mainpage constructor would be
public MainPage(MainViewModel viewModel)
THis is what happens when you open the app. But what about navigating to another page, for example public SecondPage(SecondViewModel viewModel)
Without injected viewModel I could do await App.Current.MainPage.Navigation.PushAsync(new SecondPage());
but now it gives an error becase of missing VM. So how should I approach this? Should I inject SecondViewModel
in the mainViewModel as well, and navigate to another page like await App.Current.MainPage.Navigation.PushAsync(new SecondPage(secondViewModel));
or is there any otehr way?5 Replies
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Will try to implement it like this, thanks!
why do you think that injecting VM via DI is bad?
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Idk, it seemed easier to just inject the VM and get it from the constructor (except navigating, haha), and there was no need for something like IoC Container or something like that (like I had it in Xamarin.Forms).
I was researching this a bit more, and came across AppShell, which I never used it before... The usage for navigating is pretty easy
await Shell.Current.GoToAsync("newPage")
(and ofc I have to register it in App.xaml.cs), which also gets injected objects in constructor. The downside of it is sendong some parameters when navigating to new page, but yeah...
Did u ever use AppShell? What do you think about AppShell vs NavigationPage?Unknown User•3y ago
Message Not Public
Sign In & Join Server To View