Converters in Xamarin.Forms

In Xamarin.Forms, bindings do not perform any implicit type conversions, and if you need to display a non-string object as a string you must provide a type Converter or use a StringFormat

Let us try to see this concept in action. We will try to create a Editor box which will restrict the entry length to maximum of 140 characters (Yes, just like twitter).

For this, we will have identify the restrictions,

  • "Send Tweet" button should be disabled which can be handled by the isEnabled property of the Button UI control
  • The text color of character counter should turn "Red" when the limit of 140 characters is extended. This will provide a visual indicator to user that something is going wrong.

To achieve the above conditions we will create classes that implement IValueConverter interface as below:

IntToBooleanConvertor

class IntToBooleanConvertor : IValueConverter  
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int maximumLength = System.Convert.ToInt32(parameter); //140
        return ((int) value <= maximumLength );
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

and IntToColorConverter

class IntToColorConvertor : IValueConverter  
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int maximumLength  = System.Convert.ToInt32(parameter); //140
        return ((int) value <= maximumLength ) ? Color.Green : Color.Red;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

These converters will be added to the ResourceDictionary in the Page.

TextColor of the Label applies Binding using this line of code

<Label TextColor="{Binding Source={x:Reference tweetEditor}, Path=Text.Length, Converter={StaticResource IntToColorConvertor}, ConverterParameter=140}">  

And IsEnabled of Button applies Binding using this line of code

<Button IsEnabled="{Binding Source={x:Reference tweetEditor}, Path=Text.Length, Converter={StaticResource IntToBooleanConvertor}, ConverterParameter=140}"></Button>  

Here is the complete implementation of TwitterEntry 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:local="clr-namespace:TwitterEntryDemo.Convertor;assembly=TwitterEntryDemo"
             x:Class="TwitterEntryDemo.TwitterEntry"
             Title="Twitter Entry Demo">
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:IntToBooleanConvertor x:Key="IntToBooleanConvertor"></local:IntToBooleanConvertor>
            <local:IntToColorConvertor x:Key="IntToColorConvertor"></local:IntToColorConvertor>
        </ResourceDictionary>
    </ContentPage.Resources>

    <StackLayout Orientation="Vertical">
        <Label Text="Enter your tweet : "></Label>
        <Label Text="(Minimum 140 characters)"></Label>
        <Editor x:Name="tweetEditor" HeightRequest="100"></Editor>
        <StackLayout Orientation="Horizontal">
            <Label Text="character counter : "></Label>
            <Label Text="{Binding Source={x:Reference tweetEditor}, Path=Text.Length}" TextColor="{Binding Source={x:Reference tweetEditor}, Path=Text.Length, Converter={StaticResource IntToColorConvertor}, ConverterParameter=140}"></Label>
        </StackLayout>
##        <Button Text="Send Tweet" IsEnabled="{Binding Source={x:Reference tweetEditor}, Path=Text.Length, Converter={StaticResource IntToBooleanConvertor}, ConverterParameter=140}"></Button>
    </StackLayout>

</ContentPage>  

Here are the screenshots:

In next post we will see how to implement the StringFormat binding

Complete soucecode can be found here

Happy Coding...