Boost Performance with Compiled Bindings in Xamarin.Forms

James Montemagno

Data binding is at the core of just about every Xamarin.Forms application. It enabled developers to easily bridge their user interface with their code behind form a simple markup. Data binding also simplifies user interactions and updates to the user interface automatigical! With all this awesome comes with some trade-offs. Xamarin.Forms has to analyze and resolve each binding, which can take precious CPU cycles. This is where compiled bindings come in and help boost performance when using data binding.

What are Compiled Bindings?

A compiled binding is a way of telling Xamarin.Forms at compile time of the type of data the binding is going to be using. This is means that Xamarin.Forms will not have to use any reflection at runtime to resolve the data binding. By using the special x:DataType attribute on any VisualElement you can enable a compiled binding.

Benefits

Using these bindings offer a few major benefits for you and your app:

  1. Compile-time validation for all binding expressions.
  2. Performance improvements as bindings are resolved at compile time.

Enabling XAML Compilation

A pre-requisite to use these bindings is that your app must turn on XAML Compilation. This is the default in all new apps and greatly improves performance in apps when using XAML. You can enable it by adding an assembly flag in your shared code:


[assembly:XamlCompilation(XamlCompilationOptions.Compile)]

Using Compiled Bindings

Let's use an example of a page that displays a list of Monkeys in a ListView. This means we have a Monkey with properties on it about the monkey, a MonkeysViewModel that has data objects to bind to for the list, and a MonkeysPage that is our user interface in XAML.

Here is what the user interface looks like to display a list of monkeys and the current count:


<ContentPage 
        xmlns="http://xamarin.com/schemas/2014/forms" 
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
        x:Class="Monkeys.Views.MonkeysPage"
        Title="Monkeys">
<StackLayout>
    <Label Margin="10,0" Text="{Binding MonkeyCount, StringFormat='{0} Monkeys'}"/>
    <ListView ItemsSource="{Binding Monkeys}"
            HasUnevenRows="true">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Grid Padding="10" RowSpacing="10" ColumnSpacing="10">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <controls:CircleImage 
                                BorderColor="Aqua"
                                BorderThickness="3"
                                HeightRequest="66"
                                WidthRequest="66"
                                HorizontalOptions="CenterAndExpand"
                                VerticalOptions="CenterAndExpand"
                                Aspect="AspectFill"
                                Source="{Binding Image}"/>
                        <StackLayout VerticalOptions="Center">
                            <Label Text="{Binding Name}"/>
                            <Label Text="{Binding Location}"/>
                        </StackLayout>
                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

Notice that we are binding from the MonkeysViewModel to MonkeyCount and Monkeys and additionally to the Image, Name, and Location of each monkey inside of the ItemTemplate.

To enable these bindings for the MonkeysViewModels we will bring in the namespace that it is in:

xmlns:viewmodels="clr-namespace:Monkeys.ViewModels"

Then on the ContentPage node we can add the x:DataType property:

<ContentPage 
        xmlns="http://xamarin.com/schemas/2014/forms" 
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
        x:Class="Monkeys.Views.MonkeysPage"
        xmlns:viewmodels="clr-namespace:Monkeys.ViewModels"
        x:DataType="viewmodels:MonkeysViewModel"
        Title="Monkeys">
</ContentPage>

That is all it takes to start! Now, if for some reason we have a spelling mistake in our bindings when we compile the library we will get an error as the bindings will now be validated.

Compiled Binding Error Checks for XAML

If you are using any control that has a DataTemplate you must also setup the compiled binding on it. In this app, we have a ListView that is data bound to anObservableCollection<Monkey>. We can bring in the Monkey's namespace just like we did for the MonkeysViewModel.

xmlns:models="clr-namespace:Monkeys.Models"

Then on the DataTemplate, we can specify the x:DataType like we did before:

<ListView ItemsSource="{Binding Monkeys}"
          HasUnevenRows="true">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="models:Monkey">
            <ViewCell>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

And just like that we have enabled this on our entire page and it only took a few seconds.

Learn More

There are a lot more ways to use compiled bindings in your Xamarin.Forms apps, so be sure to read through the comprehensive documentation. You can find a sample used in this blog on GitHub.

18 comments

Discussion is closed. Login to edit/delete existing comments.

  • Raphael Yaadar 0

    How do I handle Commands in a data template? I keep getting an error ‘ Command not found on the model'(specified in x:DataType of DataTemplate). The Commands are in the ViewModel

    • James MontemagnoMicrosoft employee 0

      If you are doing an ancestor binding, set the x:DataType on the control that is referencing the parent viewmodel.

  • Mark Downes 0

    Your sample images are no longer displayed on this page, or is it broken on my end?

    • James MontemagnoMicrosoft employee 0

      Thanks for the ping. We just made some changes to the syntax highlighting and that caused some issues on older blog posts. Fixed it up.

      • Mark Downes 0

        Good job – keep it up James 👍

Feedback usabilla icon