Bindable Layout – Xamarin Forms

In this post, you will learn how to use a Bindable Layout in Xamarin.Forms.

Bindable Layout 1

Xamarin.Forms is an open-source UI framework that runs on multiple platforms with a single shared codebase. It allows developers to create user interfaces in XAML with code-behind in C#. These interfaces are rendered as performant native controls on each platform.

Bindable Layout

If you are someone who is looking for a lightweight approach to display a small collection of items, however, do not wish to use ListView or CollectionView considering the memory and performance issues, then you are at the right place. You are looking for a BindableLayout.

Furthermore, Bindable layouts enable any layout class to generate its content by binding to a collection of items. Above all, it provides an option to set and customize the appearance of each item with a DataTemplate. Bindable layouts are provided by the BindableLayout class, which exposes the following attached properties:

  • ItemsSource – specifies the list of items to be displayed.
  • ItemTemplate – the DataTemplate to apply to each item in the collection of items displayed.
  • ItemTemplateSelector – the DataTemplateSelector that will be used to choose a DataTemplate for an item at runtime.

In simple terms, a bindable layout is a small version of ListView to display a series of items with the same pattern. However, the only difference is that it does not allow your items to scroll, unlike a ListView.

Setting up a Xamarin Forms Project

Check my post "Get started with Xamarin in just 10 minutes" to set up a brand new Xamarin Forms project.

Setting up the model and view model

In this article, we will see how to create and use a Bindable Layout to display the list of platforms supported by Xamarin. As a first step, lets us create the model and view model classes required for binding to the view.

Create a new class called PlatformInfo.cs and declare the below properties.

public class PlatformInfo : INotifyPropertyChanged
{
    private bool _isChecked;
    private string _platformName;

    public bool IsChecked
    {
        get { return _isChecked; }
        set { _isChecked = value; NotifyPropertyChanged(); }
    }

    public string PlatformName
    {
        get { return _platformName; }
        set { _platformName = value; NotifyPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void NotifyPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Also, create a new class called ViewModel.cs and write the below code.

public class ViewModel
{
    public ViewModel()
    {
        this.GetContactsList();
    }

    public List<PlatformInfo> PlatformsList { get; set; }

    private void GetContactsList()
    {
        if (this.PlatformsList == null)
            this.PlatformsList = new List<PlatformInfo>();

        this.PlatformsList.Add(new PlatformInfo() { IsChecked = true, PlatformName = "Android" });
        this.PlatformsList.Add(new PlatformInfo() { IsChecked = true, PlatformName = "iOS" });
        this.PlatformsList.Add(new PlatformInfo() { IsChecked = false, PlatformName = "UWP" });
    }
} 

We have created the required collection and model object for binding to a Bindable Layout. Now, let's design a UI with a Bindable Layout to display the created list.

Create a Bindable Layout

Go to MainPage.xaml and write the following code

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:BindableLayout"
             mc:Ignorable="d"
             x:Class="BindableLayout.MainPage">
    <ContentPage.BindingContext>
        <local:ViewModel />
    </ContentPage.BindingContext>
    <StackLayout x:Name="contactList" BindableLayout.ItemsSource="{Binding PlatformsList}" 
                 VerticalOptions="Center" HorizontalOptions="Center" WidthRequest="150">
        <BindableLayout.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="0.5"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="30" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <CheckBox IsChecked="{Binding IsChecked}" VerticalOptions="Center" />
                    <Label Grid.Column="1" TextColor="Black" Margin="10,0" Text="{Binding PlatformName}" IsEnabled="{Binding IsChecked}" VerticalOptions="Center">
                        <Label.Triggers>
                            <DataTrigger TargetType="Label" Binding="{Binding IsChecked}" Value="true">
                                <Setter Property="TextColor" Value="Black"/>
                            </DataTrigger>
                            <DataTrigger TargetType="Label" Binding="{Binding IsChecked}" Value="false">
                                <Setter Property="TextColor" Value="DarkGray"/>
                            </DataTrigger>
                        </Label.Triggers>
                    </Label>
                    <BoxView Grid.Row="1" Grid.ColumnSpan="2" HeightRequest="0.5" BackgroundColor="LightGray"/>
                </Grid>
            </DataTemplate>
        </BindableLayout.ItemTemplate>
    </StackLayout>
</ContentPage>

Click the "Run" button to try it out.

Bindable Layout 2

Source Code

The complete code for the sample demonstrated in this article can be found in the GitHub repository here.

Note:

Bindable layouts can be used only when the collection of items to be displayed is small, and scrolling and selection are not required. Wrap a bindable layout in a ScrollView to enable scrolling. However, it not recommended as bindable layouts lack UI virtualization. Hence, use a ListView or CollectionView in places your require scrolling. They include UI virtualization. Failure to observe this recommendation can lead to performance issues.

I hope now you have understood what is Bindable Layout and how to use it in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. Happy Coding…!