Xamarin forms binding value converter

xamarin forms binding

    Data binding typically moves data from a source value to a target value, and in certain circumstances from the target property back to the source property. When the source and target values are of the same type, or when one type can be converted to another through an implicit conversion, this transfer is easy. If this isn’t the case, a type transformation is necessary. Binding feature helps a lot while creating Xamarin Behaviours for UI functionalities.

    You learned how to transform any type into a string using the StringFormat property of a data binding in the String Formatting article. You’ll need to build some custom code in a class that implements the IValueConverter interface for various types of conversions. (An IValueConverter class in the Windows.UI.Xaml.Data namespace exists in the Universal Windows Platform, but this IValueConverter is in the Xamarin.Forms namespace.) Value converters are classes that implement IValueConverter, however, they are also referred to as binding converters or binding value converters.

The IValueConverter Interface

    Let’s assume you want to create a data binding with an int source and a bool target. When the integer source is equal to 0, you want this data binding to return false; otherwise, it should return true.   

Implement the IValueConverter:

public class IntToBoolConverter : IValueConverter

{

public object Convert(object value, Type targetType, object parameter)

{

return (int)value != 0;

}

public object ConvertBack(object value, Type targetType, object parameter)

{

return (bool)value ? 1 : 0;

}

}

This class is assigned to the Binding class types Converter value or to the Binding markup extension’s Converter element. The data binding includes this class.

When data goes from the source to the target in OneWay or TwoWay bindings, the Convert method is invoked. The object or value from the data-binding source is passed as the value parameter. The method should return a value of the data-binding target’s type. For a bool return value, the procedure converts the value parameter to an int and compares it to 0.

When data goes from the target to the source in TwoWay or OneWayToSource bindings, the ConvertBack function is invoked. ConvertBack does the inverse conversion: it assumes the value argument from the target is a bool and transforms it to an int return value for the source.

When a Button executes an activity depending on text entered into an Entry view, the Enable Buttons page displays a common requirement. The Button should be deactivated if no data has been entered into the Entry. On the IsEnabled property of each Button, there is a data binding.

The value converter is called before the result is formatted as a string if the data binding also has a StringFormat setting.

The Data Binding Demos Sample’s Enable Buttons page shows how to utilise this value converter in a data binding. The IntToBoolConverter is created in the resource dictionary of the page. It’s then used in two data bindings with a StaticResource markup extension to set the Converter property. Data converters are frequently shared throughout various data bindings on a page:

<?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:custom=”clr-namespace:Converter”

x:Class=”Converter.MainPage”>

<ContentPage.Resources>

<ResourceDictionary>

<custom:ConvertStringValueToColor x:Key=”ColorConvetor”/>

</ResourceDictionary>

</ContentPage.Resources>

<StackLayout>

<Frame BackgroundColor=”#2196F3″ Padding=”24″ CornerRadius=”0″>

<Label Text=”Convert Sti<ContentPage xmlns=”http://xamarin.com/schemas/2014/forms”

xmlns:x=”http://schemas.microsoft.com/winfx/2009/xaml”

xmlns:local=”clr-namespace:DataBindingDemos”

x:Class=”DataBindingDemos.EnableButtonsPage”

Title=”Enable Buttons”>

<ContentPage.Resources>

<ResourceDictionary>

<local:IntToBoolConverter x:Key=”intToBool” />

</ResourceDictionary>

</ContentPage.Resources>

<StackLayout Padding=”10, 0″>

<Entry x:Name=”entry1″

Text=””

Placeholder=”enter search term”

VerticalOptions=”CenterAndExpand” />

<Button Text=”Search”

HorizontalOptions=”Center”

VerticalOptions=”CenterAndExpand”

IsEnabled=”{Binding Source={x:Reference entry1},

Path=Text.Length,

Converter={StaticResource intToBool}}” />

<Entry x:Name=”entry2″

Text=””

Placeholder=”enter destination”

VerticalOptions=”CenterAndExpand” />

<Button Text=”Submit”

HorizontalOptions=”Center”

VerticalOptions=”CenterAndExpand”

IsEnabled=”{Binding Source={x:Reference entry2},

Path=Text.Length,

Converter={StaticResource intToBool}}” />

</StackLayout>

</ContentPage> rng Value To Color” HorizontalTextAlignment=”Center”

TextColor=”White” FontSize=”36″ VerticalOptions=”Center”/>

</Frame>

<Entry x:Name=”name” Placeholder=”Enter color name”  VerticalOptions=”Center”/>

<Label Text=”This Is The Color You Entered” TextColor=”{Binding Source={x:Reference name},Path=Text,

Converter={StaticResource ColorConvetor}}” FontSize=”Large” VerticalOptions=”Center”  HorizontalOptions=”CenterAndExpand”

x:Name=”label”/>

</StackLayout>

</ContentPage>

You can instantiate a value converter in the resource dictionary in the App.xaml file if it is utilized in several pages of your application.

    When a Button executes an activity depending on text entered into an Entry view, the Enable Buttons page displays a common requirement. The Button should be deactivated if no data has been entered into the Entry. On the IsEnabled property of each Button, there is a data binding. The Text property of the related Entry’s Length property serves as the data-binding source. The value converter returns true and the Button is activated if the Length property is not zero:

Figure 1: output of IValueConverter

It’s important to note that each Entry’s Text attribute is set to an empty string. Because the Text attribute is null by default, data binding will not operate.

Some value converters are designed for a particular application, while others are more generic. The ConvertBack method can simply return null if you know that a value converter will only be used in OneWay bindings.

Read More: Unlock Ui Design For your Website

The Convert method expects implicitly that the value parameter is of type int and that the return value is of type bool. The ConvertBack method, on the other hand, assumes that the value parameter is of type bool and that the return result is of type int. A runtime exception will occur if this is not the case.

Value converter can be written to be more versatile and to support a variety of data types. With the value parameter, the Convert and ConvertBack methods can utilise the as or is operators, or they can call GetType to discover the type of the parameter and then do something appropriate with it. The targetType parameter indicates the expected type of each method’s return value. Value converters are sometimes used with data bindings of several target types; the targetType argument can be used to execute a conversion for the correct type.

Binding Converter Properties

    Property and generic arguments can be added to value converter classes. This value converter translates a bool from the source to a T object for the destination:

public class BoolToObjectConverter<T> : IValueConverter

{

public T TrueObject { set; get; }

public T FalseObject { set; get; }

public object Convert(object value, Type targetType, object parameter)

{

return (bool)value ? TrueObject : FalseObject;

}

public object ConvertBack(object value, Type targetType, object parameter)

{

return ((T)value).Equals(TrueObject);

}

}

The Switch Indicators page explains how a Switching view’s values might be displayed. Although it’s usual to use value converters as resources in resource dictionaries, this page shows how to do it in a different way: Between Binding, each value converter is created. Tags for property-element converters. TrueObject and FalseObject are both set to objects of that type, and x:TypeArguments denotes the generic argument:

<ContentPage xmlns=”http://xamarin.com/schemas/2014/forms”

xmlns:x=”http://schemas.microsoft.com/winfx/2009/xaml”

xmlns:local=”clr-namespace:DataBindingDemos”

x:Class=”DataBindingDemos.SwitchIndicatorsPage”

Title=”Switch Indicators”>

<ContentPage.Resources>

<ResourceDictionary>

<Style TargetType=”Label”>

<Setter Property=”FontSize” Value=”18″ />

<Setter Property=”VerticalOptions” Value=”Center” />

</Style>

<Style TargetType=”Switch”>

<Setter Property=”VerticalOptions” Value=”Center” />

</Style>

</ResourceDictionary>

</ContentPage.Resources>

<StackLayout Padding=”10, 0″>

<StackLayout Orientation=”Horizontal”

VerticalOptions=”CenterAndExpand”>

<Label Text=”Subscribe?” />

<Switch x:Name=”switch1″ />

<Label>

<Label.Text>

<Binding Source=”{x:Reference switch1}”

Path=”IsToggled”>

<Binding.Converter>

<local:BoolToObjectConverter x:TypeArguments=”x:String”

TrueObject=”Of course!”

FalseObject=”No way!” />

</Binding.Converter>

</Binding>

</Label.Text>

</Label>

</StackLayout>

<StackLayout Orientation=”Horizontal”

VerticalOptions=”CenterAndExpand”>

<Label Text=”Allow popups?” />

<Switch x:Name=”switch2″ />

<Label>

<Label.Text>

<Binding Source=”{x:Reference switch2}”

Path=”IsToggled”>

<Binding.Converter>

<local:BoolToObjectConverter x:TypeArguments=”x:String”

TrueObject=”Yes”

FalseObject=”No” />

</Binding.Converter>

</Binding>

</Label.Text>

<Label.TextColor>

<Binding Source=”{x:Reference switch2}”

Path=”IsToggled”>

<Binding.Converter>

<local:BoolToObjectConverter x:TypeArguments=”Color”

TrueObject=”Green”

FalseObject=”Red” />

</Binding.Converter>

</Binding>

</Label.TextColor>

</Label>

</StackLayout>

<StackLayout Orientation=”Horizontal”

VerticalOptions=”CenterAndExpand”>

<Label Text=”Learn more?” />

<Switch x:Name=”switch3″ />

<Label FontSize=”18″

VerticalOptions=”Center”>

<Label.Style>

<Binding Source=”{x:Reference switch3}”

Path=”IsToggled”>

<Binding.Converter>

<local:BoolToObjectConverter x:TypeArguments=”Style”>

<local:BoolToObjectConverter.TrueObject>

<Style TargetType=”Label”>

<Setter Property=”Text” Value=”Indubitably!” />

<Setter Property=”FontAttributes” Value=”Italic, Bold” />

<Setter Property=”TextColor” Value=”Green” />

</Style>

</local:BoolToObjectConverter.TrueObject>

<local:BoolToObjectConverter.FalseObject>

<Style TargetType=”Label”>

<Setter Property=”Text” Value=”Maybe later” />

<Setter Property=”FontAttributes” Value=”None” />

<Setter Property=”TextColor” Value=”Red” />

</Style>

</local:BoolToObjectConverter.FalseObject>

</local:BoolToObjectConverter>

</Binding.Converter>

</Binding>

</Label.Style>

</Label>

</StackLayout>

</StackLayout>

</ContentPage>

The generic parameter is set to Style in the final of the three Switch and Label pairs, and full Style objects are provided for the TrueObject and FalseObject values. These alter the resource dictionary’s implicit style for Label, so the attributes in that style are explicitly given to the Label. When you toggle the Switch, the accompanying Label changes to indicate the change:

Figure 2: output of boolean to object converter

Conclusion

In this blog, we have learned the IValueConverter interface with an example, and also the Binding Converter properties and their example in this article. Technocrat and entrepreneur of a reputed Outlook Addin Development Company with years of experience in building large-scale enterprise web, cloud, and mobile applications using the latest technologies like ASP.NET, CORE, .NET MVC, Angular, and Blockchain. Keen interest in addressing business problems using the latest technologies and help organizations to achieve goals.