How to inject viewmodel into page #1540
-
I'm using UseNavigation to wire up my pages and viewmodels. I then navigate to the view model:
and it works fine. But my question is/issue is that it will instantiate the HomePage first (without a DataContext), then the HomeViewModel, and then it will set the DataContext on the HomePage to the HomeViewModel. It all works, but I have some code in the HomePage that would be more efficient if the viewmodel was injected directly into the page code-behind. If I have a constructor that takes the VM then |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
FWIW the |
Beta Was this translation helpful? Give feedback.
-
Pages and Controls shouldn't take parameters in the constructors. In theory this rule could be broken for non-Page controls, since they could be instantiated from DI before being added to the visual tree. However, this will break hot reload scenarios in the future, so best to stick with the no-parameters in constructor rule. |
Beta Was this translation helpful? Give feedback.
Pages and Controls shouldn't take parameters in the constructors. In theory this rule could be broken for non-Page controls, since they could be instantiated from DI before being added to the visual tree. However, this will break hot reload scenarios in the future, so best to stick with the no-parameters in constructor rule.
The issue with Pages is that they get instantiated by a Frame as part of Frame.Navigate. This is somewhat painful as it means the navigation code doesn't get an opportunity to set the datacontext before the Page is navigated to