Xamarin.Forms - Compiled Bindings

In this article, you will learn what Compiled Bindings in Xamarin is all about and how to use it to improve performance and avoid spelling errors.
 
Xamarin.Forms is an open-source UI framework that runs on multiple platforms with a single shared codebase. It allows developers to create user interfaces in XAML with code-behind in C#. These interfaces are rendered as performant native controls on each platform.
 

Compiled Bindings

 
If you are a Xamarin or .Net developer you would probably know what DataBinding is. It is a concept where you can dynamically load in all the pages' information at runtime when the user is navigating to a page. However, when you have pages that are really complicated that have a lot of DataBinding, then it can take a lot of time for Xamarin to look at every single element of the XAML.
 
Moreover, as a developer if you have misspelled something you probably won't know the error until you navigate to that page and see how the UI renders. Only at the runtime when the UI loads we would realize that this is not what we expect it to be. So we use the compiled bindings to solve these problems.
 
In simple words, Compiled Bindings just tells your app to compile the XAML stuff before you run the app.
 
The advantage of the Compiled Bindings are:
  • More performance
  • Catches spelling errors and other issues with data binding at compile-time and build time itself.
Prerequisites
  • Visual Studio 2017 or later (Windows or Mac) 
Let's take the XAML code from my article BindableLayout as an example for understanding what is Compiled Bindings in Xamarin.Forms.
 

Setting up a Xamarin.Forms Project

 
Let’s start by creating a new Xamarin.Forms project by following the below steps.
 
Visual Studio 2019 has more options in the launch view.
  • Clone or check out the code from any repository
  • Open a project or solution
  • Open a local folder from your computer
  • Create a new project
Choose "Create a new project".
 
 
 
Now, filter by Project Type as Mobile and choose the Mobile App (Xamarin.Forms).
 
 
 
Enter the project name that you wish. Usually, the project and solution name are the same for an app. Choose your preferred location for the project and click "Create".
 
 
 
Select the Blank App and target platforms - Android, iOS and Windows (UWP).
 
 
 
Wait for the solution to load. Expand the solution using the Solution Explorer. By default, you can see 4 projects (.NET Standard, Android, iOS and UWP).
 
Expand the .NET Standard project and select the XAML page and double-click to open the MainPage.xaml page. You now have a basic Xamarin.Forms app. Press F5 or click the run button to try it out.
 

Setting up the model and view model

 
For that first lets us create the model and view model classes required for binding to the view.
 
Create a new class called PlatformInfo.cs and declare the below properties.
  1. public class PlatformInfo    
  2. {    
  3.     public bool IsChecked { getset; }    
  4.     public string PlatformName { getset; }    
  5. }  
Create a new class called PlatformsViewModel.cs and write the below code.
  1. public class PlatformsViewModel    
  2. {    
  3.     public PlatformsViewModel()    
  4.     {    
  5.         this.GetContactsList();    
  6.     }    
  7.     
  8.     public List<PlatformInfo> PlatformsList { getset; }    
  9.     
  10.     private void GetContactsList()    
  11.     {    
  12.         if (this.PlatformsList == null)    
  13.             this.PlatformsList = new List<PlatformInfo>();    
  14.     
  15.         this.PlatformsList.Add(new PlatformInfo() { IsChecked = true, PlatformName = "Android" });    
  16.         this.PlatformsList.Add(new PlatformInfo() { IsChecked = true, PlatformName = "iOS" });    
  17.         this.PlatformsList.Add(new PlatformInfo() { IsChecked = false, PlatformName = "UWP" });    
  18.     }    
  19. }  

Setting up the user interface

 
Go to MainPage.xaml and write the following code.
  1. <?xml version="1.0" encoding="utf-8" ?>      
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"      
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"      
  4.              xmlns:d="http://xamarin.com/schemas/2014/forms/design"      
  5.              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"      
  6.              xmlns:viewModel="clr-namespace:BindableLayout.ViewModel"      
  7.              mc:Ignorable="d"      
  8.              x:Class="BindableLayout.MainPage">      
  9.     <ContentPage.BindingContext>      
  10.         <viewModel:PlatformsViewModel />      
  11.     </ContentPage.BindingContext>      
  12.     <StackLayout x:Name="contactList" BindableLayout.ItemsSource="{Binding PlatformsList}">      
  13.         <BindableLayout.ItemTemplate>      
  14.             <DataTemplate>      
  15.                 <StackLayout Orientation="Horizontal">      
  16.                     <CheckBox IsChecked="{Binding IsChecked}" VerticalOptions="Center" />      
  17.                     <Label TextColor="Black" Margin="10,0" Text="{Binding PlatformName}" VerticalOptions="Center" />      
  18.                 </StackLayout>      
  19.             </DataTemplate>      
  20.         </BindableLayout.ItemTemplate>      
  21.     </StackLayout>      
  22. </ContentPage>     
Now, you could see that I have misspelled the property name bound to the ItemsSource property. Let's try to build this project. You could see that the project is still built perfectly.
 
 
So now, let's turn on the compiled bindings to get this caught in the build time itself. The first thing to do is to our app to compile the XAML for the entire assembly. Type the below code in the MainPage.xaml.cs as shown in the below image.  
  1. [assembly:XamlCompilation(XamlCompilationOptions.Compile)]    
 
You can even skip this setting to be applied for a page(s) as shown below.
 
 
 
Now let's just go to the XAML page and tell it what to check against. The data for the XAML comes from PlatformsViewModel which is separated from the XAML front end. So we need to tell the XAML file where to find the PlatformsViewModel and that PlatformsViewModel is what it should be checking XAML data types against. We have already declared the namespace where we have the PlatformsViewModel. All we need to do is mention the data type for the content page to be of type ViewModel (2nd line in the below code snippet). 
  1. xmlns:viewModel="clr-namespace:BindableLayout.ViewModel"    
  2. x:DataType="viewModel:PlatformsViewModel"  
Let's try to build the project again.
 
That's great..! Now, you could see a build error caught in the build time itself.
 
 
Now, let's correct the property name bound to the ItemsSource of the BindableLayout from PlatformList to PlatformsList as declared in the PlatformsViewModel. Let's try to build the project again. You could still see that we are getting a build error.
 
 
The reason for this build error is we are missing an important thing here. The DataTemplate which is in the bindable layout tells the bindable layout how to display each individual item in it. Also, we could see that it has different items that are not of type PlatformsViewModel but of type PlatformInfo. So we have to do the same thing similar to the XAML file on the data template to tell them what its data type is. Insert the below codes in your XAML.  
  1. xmlns:models="clr-namespace:BindableLayout.Model"    
  1. <DataTemplate x:DataType="models:PlatformInfo">    
  2.     ...    
  3. </DataTemplate>  
Below is how the final XAML code looks.
  1. <x:DataType="viewModel:PlatformsViewModel"      
  2.          xmlns:models="clr-namespace:BindableLayout.Model"      
  3.          mc:Ignorable="d"      
  4.          x:Class="BindableLayout.MainPage">      
  5. <ContentPage.BindingContext>      
  6.     <viewModel:PlatformsViewModel />      
  7. </ContentPage.BindingContext>      
  8. <StackLayout x:Name="contactList" BindableLayout.ItemsSource="{Binding PlatformsList}">      
  9.     <BindableLayout.ItemTemplate>      
  10.         <DataTemplate x:DataType="models:PlatformInfo">      
  11.             <StackLayout Orientation="Horizontal">      
  12.                 <CheckBox IsChecked="{Binding IsChecked}" VerticalOptions="Center" />      
  13.                 <Label TextColor="Black" Margin="10,0" Text="{Binding PlatformName}" VerticalOptions="Center" />      
  14.             </StackLayout>      
  15.         </DataTemplate>      
  16.     </BindableLayout.ItemTemplate>      
  17. </StackLayout>      
  18. /ContentPage>    
Now let's just rebuild the app again. You could see that the build is succeeded now.
 
 
I hope now you have understood what is Compiled Bindings and how to use it in Xamarin.Forms.
 
Thanks for reading. Please share your comments and feedback. Happy Coding…!


Similar Articles