How do you inject a view model into a page?
Short 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.
Advertisement
AModel 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.
Likely follow-ups
- Do you need to register the page too? | How does Shell resolve pages?
Related topics