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:
- First enable XamlCompilation, by adding this attribute to your xaml class:
- 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):
[XamlCompilation(XamlCompilationOptions.Compile)]
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:
- You get compile-time errors for invalid binding expressions
- Faster compilation.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.