Pages

Sunday, June 30, 2019

Compiled binding: the performance booster you should know


In the traditional binding (classic binding), reflection is used to get the binding information, this process is costly in terms of performance, as it’s conducted in run-time.

Now Xamarin introduces a nice alternative to the classic binding, official docs says that resolving compiled binding is 8 to 20 times quicker than classic binding- a big deal!

Here’s how to enable compiled binding:

  1. First enable XamlCompilation, by adding this attribute to your xaml class:

  2. [XamlCompilation(XamlCompilationOptions.Compile)]
    You can also enable it at the assembly level.
  3. In the root element of your xaml (where you set the BindingContext on) define the x:DataType and set it to your view model (a string -not markup extension):

Example:
Code behind:


[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
    ...
}

XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:MyXam.ViewModels"
             x:Class="MyXam.MainPage"
             x:DataType="vm:MainViewModel">
    <ContentPage.BindingContext>
        <vm:MainViewModel/>
    </ContentPage.BindingContext>
    <Grid>
        <Entry Text="{Binding SingleItem.Name}" Grid.Row="0"/>
        ...
    </Grid>
</ContentPage>

one exception for this is when you use DataTemplate (in a ListView for example) where the BindingContext of the DataTemplate becomes a singular object from the ItemsSource collection, you'll need to define x:DataType on the DataTemplate:


<Grid>
    <Entry Text="{Binding SingleItem.Name}" Grid.Row="0"/>
    
    <ListView ItemsSource="{Binding Items}" Grid.Row="1">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Item">
                <ViewCell>
                    <StackLayout>
                        <Label Text="{Binding Name}"/>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

Here's why you should consider compiled binding in your next project:
  1. You get compile-time errors for invalid binding expressions
  2. Faster compilation.
It’s recommended over classic binding, and for existing projects you can switch to compiled binding easily.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

How to do code reviews correctly

Introduction Code review is a special event in the life cycle of software development, it's where ownership is transferred from the deve...