Search code examples
mvvmcross

Using MvvmCross, how do I get an "opposite" binding for a bool?


In my particular application, I would like the background to be Transparent, i.e., Transparent = true, when the IsSelected is false. I suspect I have to write a Converter, but perhaps there is an easier way?

set.Bind(selectedBox).For(v => v.Transparent).To(vm => vm.IsSelected).OneWay();

Looks like there is a WithConversion<...> possibility. Perhaps I need a NotValueConverter? Hard to believe this is not already implemented somewhere....

Update. I added the following to my Core

public class NotConverter : MvxValueConverter<bool, bool>
{
    protected override bool Convert(bool value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !value;
    }

    protected override bool ConvertBack(bool value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !value;
    }
}

but it does not seem to be picked up by the sweep and

set.Bind(selectedBox).For(v => v.Transparent).To(vm => vm.IsSelected).WithConversion("Not").OneWay();

does not make any difference.


Solution

  • Converters need to end with ValueConverter to be picked up automatically by MvvmCross. You can also use a generic type to use WithConversion.

    set.Bind(selectedBox).For(v => v.Transparent).To(vm => vm.IsSelected).WithConversion<NotConverter>().OneWay();
    

    I thought that "Not" was a built-in converter, and i've used it on Android, but i can't find anything on this so far.