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?

Update

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 :
      Visibility.Collapsed;
    return base.ConvertFrom(context, culture, value);
  }

      

}

And add this to your application:

TypeDescriptor.AddAttributes(typeof(Visibility),
  new TypeConverterAttribute(typeof(VisibilityFromBooleanConverter)));

      

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

+3


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?

+1


source


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?



+1


source


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

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

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

      

0


source







All Articles