Azzaronn
Azzaronn

Reputation: 167

Compiled bindings in Xamarin Forms

If I have a View where the BindingContext is set to my ViewModel like this:

<ContentPage ...>

<ContentPage.BindingContext>
    <vm:AddParkingSpotViewModel />
</ContentPage.BindingContext>

And then I bind my Entry value to a property like this:

<Entry Text="{Binding Address}" .../>

Is this enough to make it use compiled bindings? Or do I also have to set the x:DataType on the layout element as well?

<Grid x:DataType="vm:AddParkingSpotViewModel">

Upvotes: 1

Views: 694

Answers (1)

Cherry Bu - MSFT
Cherry Bu - MSFT

Reputation: 10346

Is this enough to make it use compiled bindings? Or do I also have to set the x:DataType on the layout element as well?

The process for using compiled bindings is to:

Enable XAML compilation. For more information about XAML compilation.

Set an x:DataType attribute on a VisualElement to the type of the object that the VisualElement and its children will bind to.

Binding expressions are only compiled for the view hierarchy that the x:DataType attribute is defined on. Conversely, any views in a hierarchy on which the x:DataType attribute is not defined will use classic bindings.

So your code is classic bindings, the following code is complied bindings:

 <ContentPage.Content>
    <Grid x:DataType="vm:AddParkingSpotViewModel">
        <Grid.BindingContext>
            <vm:AddParkingSpotViewModel />
        </Grid.BindingContext>
        <Entry Text="{Binding Address}" />
    </Grid>
</ContentPage.Content>

More detailed info about complied bindings, please take a look:

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/compiled-bindings

Upvotes: 2

Related Questions