Convert Boolean to Yes/No in XAML

 

On user interfaces, it maybe necessary to present a user-friendly version of a Boolean value. I.e. Instead of true or false, it is presented as yes or no.

With Xamarin Forms and MVVM XAML bindings, it is possible to add converters on bindings.

As can be seen in this example, it is really easy to implement!

 

In our View or Content Page (XAML) we would use a binding such as:


<Label Text="{Binding MyBooleanProperty}"/>

However, to the user, this would present the value “true” or “false”.

 

But by using a converter we would just need to use the following markup:


<Text="{Binding MyBooleanProperty, Converter={StaticResource BoolToYesNo}}"/>

In order to achieve this, a class using the IValueConverter interface just needs to be added with the methods Convert and ConvertBack.

 

 

Bool To Yes No Converter

The following code should be added to the shared project within the Xamarin solution.


public class BoolToYesNoConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (bool) value ? "Yes" : "No";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var strValue = value.ToString();
            return !string.IsNullOrWhiteSpace(strValue) && strValue.Equals("yes", StringComparison.OrdinalIgnoreCase);
        }
    }

 

 

Content Page

Next, the converter needs to be referenced within the page. The opening tag for the Content Page needs to declare the converter and then the converter itself needs to be declared in the resources.


<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyMobileApp.View.SomeContentsPage"
             xmlns:converters="clr-namespace:MyMobileApp.Converters;assembly=MyMobileApp">

    <ContentPage.Resources>
        <ResourceDictionary>
            <converters:BoolToYesNoConverter x:Key="BoolToYesNo" />
        </ResourceDictionary>
    </ContentPage.Resources>

 

 

Binding

Once the converter has been added to the shared project and the converter has been declared in the content page, it can now be used throughout the page where necessary.


<Text="{Binding MyBooleanProperty, Converter={StaticResource BoolToYesNo}}"/> 

It should even be possible to set a two-way binding and use it to set a property. That is, convert “Yes” or “No” back to a Boolean value.

 

Post Categories