Bindable layouts in Xamarin.Forms 3.5
I am probably not the only one that has created my own RepeaterView, where I extend a StackLayout or a FlexLayout so I was able to bind a collection to them and generate content based on a template.
In Xamarin.Forms 3.5 Xamarin/Microsoft introduced a new feature that they call BindableLayout. With BindableLayout it is possible to use bindings together will all Layouts that have Layout<T> as the base class.
Xamarin.Forms 3.5 is still in preview so you have to install the preview version of the NuGet package.
We will use BindableLayout as an attached property on for example StackLayout as in the code example below.
There are three properties that we can use:
- ItemsSource - The source we want to use for the binding.
- ItemTemplate - The template we want to use for each item
- ItemTemplateSelector - If we want to use a template selector to use multiple templates based on the data.
BindableLayout can be very useful in some scenarios, mostly for short lists where we don't want the behavior from a ListView, for example, we don't always want builtin scroll. If the scroll is needed we can use ScrollView for the whole page. Another use case can be if we want to have a list inside a ListView, ListViews inside a ListView is not a good idea, but a StackLayout with binding to a collection with a few items will be fine. For larger collections, I will recommend using ListView or the CollectionView that will be introduced in Xamarin.Forms 4.0, because they are more optimized from a performance point of view.
Below is a screenshot from an iOS app that using the code above:
Do you want to read more about BindableLayout, you can read this post on the official Xamarin blog.