Why can't a boolean conversion be converted to visibility in a binding without having to create a BooleanToVisibilityConverter?

It seems odd that a binding cannot convert a boolean to default visibility without having to provide a BooleanToVisibilityConverter all the time. Does anyone know why?


I found a way to do it now:

Create a TypeConverter like this:

public class VisibilityFromBooleanConverter : TypeConverter
  public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    if (sourceType == typeof(Boolean)) return true;
    return base.CanConvertFrom(context, sourceType);

  public override object ConvertFrom(ITypeDescriptorContext context,
    System.Globalization.CultureInfo culture, object value)
    if (value is Boolean) return ((Boolean)value) ? Visibility.Visible :
    return base.ConvertFrom(context, culture, value);



And add this to your application:

  new TypeConverterAttribute(typeof(VisibilityFromBooleanConverter)));


Everything seems to work fine. Now you don't need to supply BooleanToVisibilityConverter for every boolean binding.


source to share

3 answers

There are three possibilities for Visibility:

  • Visible

  • Hidden

  • Collapsed

How do you convert something with two states to something with three?



Because logical and visiblitiy do not have the same type in the back. And there are 2 states that are not visible → "hidden" and "collapsed". Based on what WPF decides what do you want?



This is purely informational, but it doesn't need to use a converter

<Button x:Name="TestButton" Content="Test" Width="110" Height="26">
    <Style TargetType="{x:Type Button}">
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=IsEnabled}" Value="False">
          <Setter Property="Visibility" Value="Hidden"/>

<CheckBox IsChecked="{Binding ElementName=TestButton, Path=IsEnabled}" Width="110" Height="23" Content="Check me" Margin="280,108,49,104" />




All Articles