Xamarin.Forms - Bindable Layout

In this article, you will learn how to use a Bindable Layout in Xamarin.Forms.
 
Xamarin.Forms - Bindable Layout
 
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 Bindable Layout.
 
Bindable layouts enable any layout class to generate its content by binding to a collection of items. 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 – specifies the DataTemplate to apply to each item in the collection of items displayed.
  • ItemTemplateSelector – specifies 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 the Bindable Layout does not allow your items to scroll, unlike ListView.
 
Prerequisites
  • Visual Studio 2017 or later (Windows or Mac) 

Setting up a Xamarin.Forms Project

 
Let’s start by creating a new Xamarin.Forms project by following the below steps. 
 
Visual Studio 2019 has more options in the launch view.
  • Clone or check out the code from any repository 
  • Open a project or solution
  • Open a local folder from your computer
  • Create a new project
Choose "Create a new project".
 
Xamarin.Forms - Bindable Layout
 
Now, filter by Project Type as Mobile and choose the Mobile App (Xamarin.Forms).
 
Xamarin.Forms - Bindable Layout
 
Enter the project name of your wish. Usually, the project and solution name are the same for an app. Choose your preferred location for the project and click "Create". 
 
Xamarin.Forms - Bindable Layout
 
Select the Blank App and target platforms - Android, iOS and Windows (UWP).
 
Xamarin.Forms - Bindable Layout
 
Wait for the solution to load. Expand the solution using the Solution Explorer. By default, you can see 4 projects (.NET Standard, Android, iOS and UWP).
 
Expand the .NET Standard project and select the XAML page and double-click to open the MainPage.xaml page. You now have a basic Xamarin.Forms app. Press F5 or click the run button to try it out.
 

Create a Bindable Layout

 
In this article, we will see how to create and use a Bindable Layout to display the list of platforms supported by Xamarin. For that first 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.
  1. public class PlatformInfo : INotifyPropertyChanged  
  2. {  
  3.     private bool _isChecked;  
  4.     private string _platformName;  
  5.   
  6.     public bool IsChecked  
  7.     {  
  8.         get { return _isChecked; }  
  9.         set { _isChecked = value; NotifyPropertyChanged(); }  
  10.     }  
  11.   
  12.     public string PlatformName  
  13.     {  
  14.         get { return _platformName; }  
  15.         set { _platformName = value; NotifyPropertyChanged(); }  
  16.     }  
  17.   
  18.     public event PropertyChangedEventHandler PropertyChanged;  
  19.     public void NotifyPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")  
  20.     {  
  21.         if (this.PropertyChanged != null)  
  22.             this.PropertyChanged(thisnew PropertyChangedEventArgs(propertyName));  
  23.     }  
  24. }  
Create a new class called ViewModel.cs and write the below code.
  1. public class ViewModel  
  2. {  
  3.     public ViewModel()  
  4.     {  
  5.         this.GetContactsList();  
  6.     }  
  7.   
  8.     public List<PlatformInfo> PlatformsList { getset; }  
  9.   
  10.     private void GetContactsList()  
  11.     {  
  12.         if (this.PlatformsList == null)  
  13.             this.PlatformsList = new List<PlatformInfo>();  
  14.   
  15.         this.PlatformsList.Add(new PlatformInfo() { IsChecked = true, PlatformName = "Android" });  
  16.         this.PlatformsList.Add(new PlatformInfo() { IsChecked = true, PlatformName = "iOS" });  
  17.         this.PlatformsList.Add(new PlatformInfo() { IsChecked = false, PlatformName = "UWP" });  
  18.     }  
  19. }  
We have created the required collection and model object for binding to a Bindable Layout. Now, let's design an UI with Bindable Layout to display the created list. 
 

Setting up the user interface

 
Go to MainPage.xaml and write the following code.
 
MainPage.xaml 
  1. <?xml version="1.0" encoding="utf-8" ?>    
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"    
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"    
  4.              xmlns:d="http://xamarin.com/schemas/2014/forms/design"    
  5.              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
  6.              xmlns:local="clr-namespace:BindableLayout"    
  7.              mc:Ignorable="d"    
  8.              x:Class="BindableLayout.MainPage">    
  9.     <ContentPage.BindingContext>    
  10.         <local:ViewModel />    
  11.     </ContentPage.BindingContext>    
  12.     <StackLayout x:Name="contactList" BindableLayout.ItemsSource="{Binding PlatformsList}"     
  13.                  VerticalOptions="Center" HorizontalOptions="Center" WidthRequest="150">    
  14.         <BindableLayout.ItemTemplate>    
  15.             <DataTemplate>    
  16.                 <Grid>    
  17.                     <Grid.RowDefinitions>    
  18.                         <RowDefinition Height="Auto"/>    
  19.                         <RowDefinition Height="0.5"/>    
  20.                     </Grid.RowDefinitions>    
  21.                     <Grid.ColumnDefinitions>    
  22.                         <ColumnDefinition Width="30" />    
  23.                         <ColumnDefinition Width="*" />    
  24.                     </Grid.ColumnDefinitions>    
  25.                     <CheckBox IsChecked="{Binding IsChecked}" VerticalOptions="Center" />    
  26.                     <Label Grid.Column="1" TextColor="Black" Margin="10,0" Text="{Binding PlatformName}" IsEnabled="{Binding IsChecked}" VerticalOptions="Center">    
  27.                         <Label.Triggers>    
  28.                             <DataTrigger TargetType="Label" Binding="{Binding IsChecked}" Value="true">    
  29.                                 <Setter Property="TextColor" Value="Black"/>    
  30.                             </DataTrigger>    
  31.                             <DataTrigger TargetType="Label" Binding="{Binding IsChecked}" Value="false">    
  32.                                 <Setter Property="TextColor" Value="DarkGray"/>    
  33.                             </DataTrigger>    
  34.                         </Label.Triggers>    
  35.                     </Label>    
  36.                     <BoxView Grid.Row="1" Grid.ColumnSpan="2" HeightRequest="0.5" BackgroundColor="LightGray"/>    
  37.                 </Grid>    
  38.             </DataTemplate>    
  39.         </BindableLayout.ItemTemplate>    
  40.     </StackLayout>    
  41. </ContentPage>     
Click the "Run" button to try it out.
 
Xamarin.Forms - Bindable Layout
 
Note
Bindable layouts should only be used when the collection of items to be displayed is small, and scrolling and selection aren't required. While scrolling can be provided by wrapping a bindable layout in a ScrollView, this is not recommended as bindable layouts lack UI virtualization. When scrolling is required, a scrollable view that includes UI virtualization, such as ListView or CollectionView, should be used. 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…!


Similar Articles