There are many best practices in writing Xamarin. Here are some that we’ve canonized where I work…
👍 By convention the identifier for the ViewModel is vm
😠 Do not assign more than one page to a view model. Generally speaking: it should be one page to one view model
😠 Do not pass view modes to methods of other pages
👍 The only code in code-behind (e.g., foo.xaml.cs) should be
- initialize in the constructor
- create the view model
- assign the datacontext to the view model
- call the viewmodel’s Initialize method
- Lifecycle methods such as OnAppearing and OnDisappearing
Why: we want to keep the code behind as sparse as possible. Unit testing requires reaching into code and that is infinitely easier with a viewmodel.
👍 Every ViewModel should have an initialize method.
Why: Having an initialize method keeps most of the code for the vm out of the constructor. This is recommended practice by Microsoft, and allows for async methods.
😠 Do not put Xaml in templates in App.xaml. Put the Xaml in the Xaml file.
Why: App.xaml quickly becomes bloated and hard to work with. Having the Xaml in the Xaml file is natural and helps create the troika we want: foo.xaml, foo.xaml.cs and fooViewModel.cs.
👍 Create viewmodel name by appending “viewmodel” to the xaml name
LigthController.xaml
LightController.xaml.cs
LightControllerViewModel.cs
Why: It is far easier to find the file you want if we follow a convention.
😠 Avoid Xaml file names ending in “view”
LightControllerView.xaml
LightControllerView.xaml.cs
LightControllerViewViewModel.cs
Why: Adding view to a view file is redundant and it makes reading the name of the ViewModel more difficult.
👍 Use commands rather than event handlers
// wrong - handled in code behind
<button Text="Divide by 2" Clicked="onClick" />
//correct - handled in viewmodel
<button Text="Divide by 2" ClickedCommand="{Binding DivideBy2Command"
Why: It is much easier to write unit tests when the event handler is in the viewmodel.