Back to results for “Dependency injection”
.NET MAUI › Dependency Injection & Services

How do you inject a view model into a page?

Intermediate

Answer

Register both the page and the view model in DI, then take the view model as a constructor parameter of the page and assign it to BindingContext. Because the page is resolved from the container (e.g., via Shell route registration or GoToAsync), the view model is injected automatically.
public MainPage(MainViewModel vm)
{
    InitializeComponent();
    BindingContext = vm;
}
Real-world example Navigating to MainPage yields a fully wired view model with its repository and logger injected, without service-locator calls.

Common follow-ups: Do you need to register the page too? | How does Shell resolve pages?