In Xamarin.Forms 3.5 the BindableLayout was introduced in order to provide functionality similar to a “repeater.” In nearly every Xamarin project I’ve worked on, I’ve needed a repeater of some sort. So, I’d usually create a custom control for this, which would take an ItemsSource and an ItemTemplate, but I don’t have to anymore. This functionality was introduced in Xamarin.Forms 3.5.

While many of the use cases I was solving for with my own “repeater” can now be solved by the Bindable StackLayout, I feel like we are overlooking that the BindableLayout isn’t just for the StackLayout. In fact, it’s for anything that derives from Layout. This is awesome, because it means that the following layouts, can all have a bindable set of items:

I have to admit, I haven’t figured out all of the potential use cases for binding these different types of layouts, but the main one that comes to mind is the FlexLayout. The FlexLayout was introduced back in Xamarin.Forms 3.1, and provides a couple of awesome features allowing your layouts to automatically space and distribute evenly accross different device types.

While the following example is nearly the same as the example in the blog post announcing BindableLayout’s, I feel that other layout types deserve a little love too. So, let’s go ahead and use a Bindable FlexLayout.

<ScrollView>
    <FlexLayout
        BindableLayout.ItemsSource="{Binding Items}"
        Wrap="Wrap"
        Direction="Row"
        JustifyContent="Center"
        AlignItems="Center"
        AlignContent="Start">
        <BindableLayout.ItemTemplate>
            <DataTemplate>
                <StackLayout Orientation="Horizontal">
                    <Label
                        Text="{Binding Name}"
                        HorizontalOptions="StartAndExpand" />
                    <Label
                        Text="{Binding Author}"
                        HorizontalOptions="EndAndExpand" />
                </StackLayout>
            </DataTemplate>
        </BindableLayout.ItemTemplate>
    </FlexLayout>
</ScrollView>

There are a couple of key parts that make the above example work. You are probably familair with them if you’ve used the ListView before.

  1. BindableLayout.ItemsSource="{Binding Items}" - This line specifies an ItemsSource IEnumerable which provides the “repeater” functionality for whatever list of items you provide.
  2. <BindableLayout.ItemTemplate> - This provides the template for each item that is bound. Above we have two labels with name and author information.
  3. ScrollView - The FlexLayout does not automatically provide scroll functionality for when there are too many items to fit onscreen, so we wrap the layout in a ScrollView.

And that’s it. We now have a view that is bound to our list of objects, and will resize automatically across layouts and device types.

@jtaubensee