Press ESC to close

Xamarin Forms Converter

Hello friends. In this article I will talk about how to create converter with Xamarin.Forms. First of all, if you ask what is converter; You may think of converting a value to a different value depending on the situation. For example, you put more than 2 views on the grid and upper base. If you want only one of these views to appear, you must write Converter for others. While the visibility of the views is false, the other must be true with a converter.

We create a class for this. In order for this class to be a converter, it must inherit from the IValueConverter class. After inheritance, we must include 2 functions in the class. These functions are Convert and ConvertBack functions. The convert function works the first time it is bind. The Convert Back method works if the item binding is two ways.

In the example I’ll give, I’m going to make the value null. So I will prevent the application from failing when I use LisView. The first parameter of the convert function is the corresponding value. I check this value and continue my operations. I check the value with a short if else and return the other one if it is false.

public class NullToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value == null ? false : value;
        }

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

Of course, that’s not all. We need to tell the control we’re going to get on this. Of course, before that I have to specify the location of my converter on xaml side. After specifying the converter folder, we give it to the control we bind as converter. It’s actually that simple. You can check it step by step using Breakpoint.

<?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:XamConverter" 
             x:Class="XamConverter.MainPage"
             xmlns:converter="clr-namespace:XamConverter.Converters"
             BackgroundColor="Gray">
    <ContentPage.Resources>
        <ResourceDictionary>
            <converter:NullToVisibilityConverter x:Key="nullToVisibilityConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <StackLayout VerticalOptions="CenterAndExpand"
                 Padding="40">
        
        <Entry Text="{Binding Name}"/>
        
        <Button Text="Enter"
                IsVisible="{Binding Name, Converter={StaticResource nullToVisibilityConverter}}"/>
    </StackLayout>
</ContentPage>

If you have questions, you can reach us by comment or e-mail. Good work.

Leave a Reply

Your email address will not be published. Required fields are marked *