Hello Devz,

WPF is providing a really useful converter called BooleanToVisibilityConverter. But the thing with this converter is that it’s really limited. Let’s say we want to use the same boolean to show one control and collapse another one, we just can’t…

Here is new version of this converter that can accept a parameter to invert the boolean when needed:

public sealed class ParametrizedBooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool flag = false;

        if (value is bool)
            flag = (bool)value;
        else
        {
            if (value is bool?)
            {
                bool? flag2 = (bool?)value;
                flag = (flag2.HasValue && flag2.Value);
            }
        }

        //If false is passed as a converter parameter then reverse the value of input value
        if (parameter != null)
        {
            bool par = true;
            if ((bool.TryParse(parameter.ToString(), out par)) && (!par)) flag = !flag;
        }

        return flag ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is Visibility)
            return (Visibility)value == Visibility.Visible;

        return false;
    }

    public ParametrizedBooleanToVisibilityConverter()
    {
    }
}

Usage:

<UserControl.Resources>
    <converters:ParametrizedBooleanToVisibilityConverter x:Key="ParametrizedBooleanToVisibilityConverter"/>
</UserControl.Resources>

...

Visibility="{Binding MyBooleanValue, Converter={StaticResource ParametrizedBooleanToVisibilityConverter}, ConverterParameter=false}"/>

You will notice the ConverterParameter=false which allows the invertion of the boolean value.

Happy coding!  🙂