xaml Converters Creating and using a Converter: BooleanToVisibilityConverter and InvertibleBooleanToVisibilityConverter


Example

To extend and expand upon the binding experience we have converters to convert one a value of one type into another value of another type. To leverage Converters in a Databinding you first need to create a DataConverter class tht extens either

  • IValueConverter(WPF & UWP)

or

  • IMultiValueConverter(WPF)

if you want to convert multiple types into one type
In this case we focus on converting a boolean True/False value to the correspionding Visibilities Visibility.Visible and Visibility.Collapsed:

public class BooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return (value is bool && (bool) value) ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return (value is Visibility && (Visibility) value == Visibility.Visible);
    }
}

The Convert method is called whenever you GET data FROM the ViewModel.
The ConvertBack is called upon SET ing data TO the ViewModel for BindingMode.TwoWay bindings.

Of course you can also utilize properties within your converter. Take a look at this one:

public class InvertibleBooleanToVisibilityConverter : IValueConverter
{
    public bool Invert { get; set; } = false;

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return (value is bool && (bool) value != Invert) ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return (value is Visibility && ((Visibility) value == Visibility.Visible) != Invert);
    }
}

If you want to use a converter in a Binding, simply declare it as a resource in your page, window, or other element, give it a key and supply potentially needed properties:

<Page ...
    xmlns:converters="using:MyNamespce.Converters">
<Page.Resources>
    <converters:InvertibleBooleanToVisibilityConverter 
        x:Key="BooleanToVisibilityConverter" 
        Invert="False" />
</Page.Resources>

and use it as a StaticResource in a binding:

<ProgressRing 
        Visibility="{Binding ShowBusyIndicator, 
            Converter={StaticResource BooleanToVisibilityConverter},
            UpdateSourceTrigger=PropertyChanged,
            Mode=OneWay}" />