Xamarin Forms Lambda To Boolean Converter

Hi there!

Ever had the issue to convert a more or less complex lambda expression into a boolean in a Xamarin Forms view?

Like « I want to show something only for a property that matches my condition »?

Ever had the error: System.ArgumentException: Invalid expression type?


/!\ Warning: this article could cause severe bleeding for the eyes of the purist. This is kind of a hack. I know that. Defining a lambda in the view, etc. /!\


Well seek no more my friend, here is the LambdaToBooleanConverter:

public class LambdaToBooleanConverter<T> : IValueConverter  
{
    public Func<T, bool> Lambda { get; set; }

    public object Convert(object value, Type targetType, 
                          object parameter, CultureInfo culture)
    {
        var valueT = (T)value;
        return Lambda(valueT);
    }

    public object ConvertBack(object value, Type targetType, 
                              object parameter, CultureInfo culture)
    {
        throw new NotSupportedException(); // not relevant.
    }
}

You can use this in your view like that:

var isVisibleConverter = new LambdaToBooleanConverter<User>()  
    { 
        Lambda = u => u.Status == Status.Admin 
    };

myControl.SetBinding<MyObservableObject>(MyControl.IsVisibleProperty,  
                                         o => o.User, 
                                         converter: isVisibleConverter);

Remember to bind on the element that implements the INotifyPropertyChanged.

XAML-side: you might need to declare it in code-behind (not a big fan of the solution).


This is probably not efficient in terms of performance but it does the job.

Do not use and abuse complex lambdas: if it is too complex you are probably doing something wrong.

Do not uselessly declare more than once your converters.

This only solves a minor use-case I had that I did not want to refactor. I my case it was an ObservableObject that added commands to a DTO.
I did not wanted to re-create every property of the DTO but still wanted to bind an expression of the DTO.


Paul, out!