Xamarin Coding Standards

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.

Unknown's avatar

About Jesse Liberty

** Note ** Jesse is currently looking for a new position. You can learn more about him at https://jesseliberty.bio Thank you. Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET, is now available wherever you buy your books. Liberty was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 13 year Microsoft MVP.
This entry was posted in Essentials and tagged , , . Bookmark the permalink.