Learn About Data Binding In Xamarin.Forms

DATA BINDING 

What is data binding?

Data binding is used for linking two objects. This is used to reflect changes: If a change in one property occurs than it automatically reflects in the other property. Data binding is the main part of MVVM (Model-View-ViewModel).

DATA BINDING

The main benefit of Data binding is that you no longer have to worry about synchronizing the data between your views and data source.

Binding has several properties including.

  • Path
  • Mode

Binding Path

The Path is used to specify property name of the source object, which is used for binding.

Binding Mode

The Mode is used to provide the direction in which property value changes are made.

  • OneWay
    In One-way binding, the changes are made from its source to the target.
  • TwoWay
    In Two-way binding, the changes are made in both the directions and Two-way binding makes sure that the source and the target are always synchronized.
  • OneWayToSource
    Changes are made from the target to the source and are mainly used for read-only bindable properties.

In Xamarin.Forms the mode property is set to OneWay by default.

View to View Binding

Here, we can link properties of two views on a single page.

Let’s go through an example.

XAML

  1. <StackLayout>    
  2.     <Slider x:Name="slider" Maximum="360"></Slider>    
  3.     <Label Text="Rotation"    
  4.            BindingContext="{x:Reference Name=slider}"    
  5.            Rotation="{Binding Path=Value}"    
  6.            HorizontalOptions="CenterAndExpand"    
  7.            ></Label>    
  8. </StackLayout>   
Here, we bind the value property of slider with rotation property of the label with Oneway binding, which is set by default. So, when we move the slider, the label starts rotating and maximum value of slider is set to 360.

The Output on an Android and Windows desktop is given below.

DATA BINDING

For Your Practice

Bind Entry text with label text

Binding and Collections

You can also bind collections through data binding. If you have to bind a lot of data to view then binding does its part and helps you sync data. It doesn't matter if  data is coming from some API or DB or from any other source, you can still bind it with the collection or with a single view.

Let’s bind a collection of data and see how data binding make our work better managed and easier.

Here we are going to bind a list view. Firstly we are going to make a list in XAML and then bind this list.

You can bind a simple list with data and you can also make data template and cells in a list to manage your data.

Some different type of cells in the list are:

  • View Cell
  • Text Cell
  • Image Cell
  • Switch Cell
  • Entry Cell

To make a simple list:

List View - XAML

  1. <ListView>  
  2. </ListView>  

Now make some data and set it on the list.

Code

  1. public List<string> ListData { get; set; }  
  2. public MainPage()  
  3.         {  
  4.   
  5.             ListData = new List<string>()  
  6.             {  
  7.                 "String a",  
  8.                 "String b",  
  9.                 "String c",  
  10.                 "String d",  
  11.                 "String e",  
  12.                 "String f",  
  13.             };  
  14.   
  15.             InitializeComponent();  
  16.   
  17.         }  

Now set item source of a list; you can set item source property both from XAML and from code. 

Set item source from XAML and Code,

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:local="clr-namespace:XamarinWebExamples"  
  5.              x:Class="XamarinWebExamples.MainPage" x:Name="MainPage">  
  6.   
  7.     <ListView x:Name="list"  
  8.               ItemsSource="{Binding ListData, Source={x:Reference MainPage}}">  
  9.     </ListView>  
  10.   
  11. </ContentPage>  

And from code:

Code

list.ItemsSource = ListData;

Output

DATA BINDING

List View Cells - 
XAML

 

  1. <ListView.ItemTemplate>  
  2.     <DataTemplate>  
  3.         <TextCell Detail="{Binding Details}" Text="{Binding Name}"/>  
  4.     </DataTemplate>  
  5. </ListView.ItemTemplate>  
  6. /ListView>  

Code

  1.     public partial class MainPage : ContentPage  
  2.     {  
  3.         public ObservableCollection<DataClass> Data { get; set; }  
  4.   
  5.         
  6.         public MainPage()  
  7.         {  
  8.             Data = new ObservableCollection<DataClass>()  
  9.             {  
  10.                 new DataClass(){ id = 0, Name = "Umair", Details = "Engineer" },  
  11.                 new DataClass(){ id = 0, Name = "Hassan", Details = "Developer" },  
  12.                 new DataClass(){ id = 0, Name = "Saleh", Details = "Designer" },  
  13.                 new DataClass(){ id = 0, Name = "Sanat", Details = "Teacher" },  
  14.                 new DataClass(){ id = 0, Name = "Mehmood", Details = "Business Man" },  
  15.             };  
  16.   
  17.             InitializeComponent();  
  18.         }  
  19.     }  
  20. public class DataClass  
  21.     {  
  22.         public int id { get; set; }  
  23.         public string Name { get; set; }  
  24.         public string Details { get; set; }  
  25.   
  26.     }  
  27. }  

Output 

DATA BINDING

For Your Practice

Make an image cell in a list and bind it.

Binding Value Converters

You can also attach converters with values and convert values from these converters. By adding a converter your original value is passed to the converter and converter returns the modified value. And then the new modified value is displayed or used instead of the original value.

Let’s go through its example to make a converter. Firstly we can make a class and then implement this class with IValueConverter interface. After implementation, our converter is ready to use.

Implement a converter

  1. namespace XamarinWebExamples  
  2. {  
  3.     public class ValueConverterExample : IValueConverter  
  4.     {  
  5.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
  6.         {  
  7.              if (string.IsNullOrEmpty(value.ToString()))  
  8.                 return "-";  
  9.             return value;     
  10.  }  
  11.   
  12.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
  13.         {  
  14.             throw new NotImplementedException();  
  15.         }  
  16.     }  
  17. }  

Here we make a simple converter whose purpose is to check null or empty values. And if any value is null or empty then it will return a hyphen. So by this converter null values return a hyphen. Now use this converter in XAML.

To use a converter in XAML you have to define this converter in application resource or in page resource. Here we are declaring this converter in page resource directory and then using it.

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:local="clr-namespace:XamarinWebExamples"  
  5.              x:Class="XamarinWebExamples.MainPage" x:Name="MainPage">  
  6.     <ContentPage.Resources>  
  7.         <ResourceDictionary>  
  8.             <local:ValueConverterExample x:Key="ValueConverterExample" />  
  9.         </ResourceDictionary>  
  10.     </ContentPage.Resources>  
  11.   
  12.     <ListView ItemsSource="{Binding Data, Source={x:Reference MainPage}}">  
  13.         <ListView.ItemTemplate>  
  14.             <DataTemplate>  
  15.                 <TextCell DetailColor="Black" TextColor="Black"  
  16.  Detail="{Binding Details, Converter={StaticResource ValueConverterExample}" Text="{Binding Name, Converter={StaticResource ValueConverterExample}"/>  
  17.             </DataTemplate>  
  18.         </ListView.ItemTemplate>  
  19.     </ListView>  
  20.   
  21. </ContentPage>  

So, here we define resource directory on our page. And in a list view, we bind a list and attach converters with it. Let’s test our converter and add some null values in the list and run the program.

Output

DATA BINDING

 

Our converter is working fine and displaying hyphen on null or empty values.

Parameters

You can also pass a parameter with converter and utilize it according to your work. To pass a converter parameter:

XAML

  1. <Label Text="{Binding test, Converter={StaticResource ValueConverterExample}, ConverterParameter='Any Parameter'}"/>  

This parameter is now received in your converter and you can perform your desired actions according to your parameters.

For Your Practice

Make a converter to invert Boolean values.

Binding Commands

You can bind commands with elements and also send command parameters. Command will perform a given action whenever it is called.

Let’s go through its example. Here we make a simple command and bind it with a button. When the button is clicked the command starts its execution and sets the item source of a list.

Code

  1. public Command BindData { get; set; }  
  2.      public MainPage()  
  3.      {  
  4.          BindingContext = this;  
  5.          Data = new ObservableCollection<DataClass>()  
  6.          {  
  7.              new DataClass(){ id = 0, Name = "Umair", Details = "Engineer" },  
  8.              new DataClass(){ id = 0, Name = "", Details = "Developer" },  
  9.              new DataClass(){ id = 0, Name = "Saleh", Details = "Designer" },  
  10.              new DataClass(){ id = 0, Name = "", Details = "Teacher" },  
  11.              new DataClass(){ id = 0, Name = "Mehmood", Details = "" },  
  12.          };  
  13.   
  14.          BindData = new Command(() => { list.ItemsSource = Data; });  
  15.          InitializeComponent();          
  16.      }  

Here we make a command named BindData and this command can set the  item source of a list when executed.

Now bind it in XAML.

XAML

  1. <StackLayout Orientation="Vertical">  
  2.     <Button Text="BindData" Command="{Binding BindData, Source={x:Reference MainPage}}"/>  
  3.     <ListView x:Name="list">  
  4.         <ListView.ItemTemplate>  
  5.             <DataTemplate>  
  6.                 <TextCell DetailColor="Black" TextColor="Black" Detail="{Binding Details,  
  7.                 Converter={StaticResource ValueConverterExample}"  
  8.                       Text="{Binding Name, Converter={StaticResource ValueConverterExample}"/>  
  9.             </DataTemplate>  
  10.         </ListView.ItemTemplate>  
  11.     </ListView>  
  12. </StackLayout>  

Output

DATA BINDING

 

Now, click on the button, a command is performed and item source of the list is set.

DATA BINDING

 

For Your Practice

Make a command which displays the next page of your app.


Similar Articles