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).
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.
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
- <StackLayout>
- <Slider x:Name="slider" Maximum="360"></Slider>
- <Label Text="Rotation"
- BindingContext="{x:Reference Name=slider}"
- Rotation="{Binding Path=Value}"
- HorizontalOptions="CenterAndExpand"
- ></Label>
- </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.
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
Now make some data and set it on the list.
Code
- public List<string> ListData { get; set; }
- public MainPage()
- {
-
- ListData = new List<string>()
- {
- "String a",
- "String b",
- "String c",
- "String d",
- "String e",
- "String f",
- };
-
- InitializeComponent();
-
- }
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
- <?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:local="clr-namespace:XamarinWebExamples"
- x:Class="XamarinWebExamples.MainPage" x:Name="MainPage">
-
- <ListView x:Name="list"
- ItemsSource="{Binding ListData, Source={x:Reference MainPage}}">
- </ListView>
-
- </ContentPage>
And from code:
Code
list.ItemsSource = ListData;
Output
List View Cells - XAML
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextCell Detail="{Binding Details}" Text="{Binding Name}"/>
- </DataTemplate>
- </ListView.ItemTemplate>
- /ListView>
Code
- public partial class MainPage : ContentPage
- {
- public ObservableCollection<DataClass> Data { get; set; }
-
-
- public MainPage()
- {
- Data = new ObservableCollection<DataClass>()
- {
- new DataClass(){ id = 0, Name = "Umair", Details = "Engineer" },
- new DataClass(){ id = 0, Name = "Hassan", Details = "Developer" },
- new DataClass(){ id = 0, Name = "Saleh", Details = "Designer" },
- new DataClass(){ id = 0, Name = "Sanat", Details = "Teacher" },
- new DataClass(){ id = 0, Name = "Mehmood", Details = "Business Man" },
- };
-
- InitializeComponent();
- }
- }
- public class DataClass
- {
- public int id { get; set; }
- public string Name { get; set; }
- public string Details { get; set; }
-
- }
- }
Output
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
- namespace XamarinWebExamples
- {
- public class ValueConverterExample : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (string.IsNullOrEmpty(value.ToString()))
- return "-";
- return value;
- }
-
- public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- }
- }
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
- <?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:local="clr-namespace:XamarinWebExamples"
- x:Class="XamarinWebExamples.MainPage" x:Name="MainPage">
- <ContentPage.Resources>
- <ResourceDictionary>
- <local:ValueConverterExample x:Key="ValueConverterExample" />
- </ResourceDictionary>
- </ContentPage.Resources>
-
- <ListView ItemsSource="{Binding Data, Source={x:Reference MainPage}}">
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextCell DetailColor="Black" TextColor="Black"
- Detail="{Binding Details, Converter={StaticResource ValueConverterExample}" Text="{Binding Name, Converter={StaticResource ValueConverterExample}"/>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
-
- </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
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
- <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
- public Command BindData { get; set; }
- public MainPage()
- {
- BindingContext = this;
- Data = new ObservableCollection<DataClass>()
- {
- new DataClass(){ id = 0, Name = "Umair", Details = "Engineer" },
- new DataClass(){ id = 0, Name = "", Details = "Developer" },
- new DataClass(){ id = 0, Name = "Saleh", Details = "Designer" },
- new DataClass(){ id = 0, Name = "", Details = "Teacher" },
- new DataClass(){ id = 0, Name = "Mehmood", Details = "" },
- };
-
- BindData = new Command(() => { list.ItemsSource = Data; });
- InitializeComponent();
- }
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
- <StackLayout Orientation="Vertical">
- <Button Text="BindData" Command="{Binding BindData, Source={x:Reference MainPage}}"/>
- <ListView x:Name="list">
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextCell DetailColor="Black" TextColor="Black" Detail="{Binding Details,
- Converter={StaticResource ValueConverterExample}"
- Text="{Binding Name, Converter={StaticResource ValueConverterExample}"/>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- </StackLayout>
Output
Now, click on the button, a command is performed and item source of the list is set.
For Your Practice | Make a command which displays the next page of your app. |