Andreas Zita
Andreas Zita

Reputation: 7580

Why can't a Boolean be converted to Visibility in a Binding without having to supply a BooleanToVisibilityConverter?

It seem strange that a binding can't convert a boolean to visibility by default without having to supply a BooleanToVisibilityConverter everytime everywhere. Anyone know why?

Update

I've found a way to do this 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 app:

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

It seem to work just fine. Now you don't have to supply a BooleanToVisibilityConverter for every boolean-binding.

Upvotes: 3

Views: 605

Answers (2)

Martin Moser
Martin Moser

Reputation: 6267

Because boolean and visiblitiy don't have the same type in the back. And there are 2 states which are not visible -> "hidden" and "collapsed". Based on what should WPF decide what you want?

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174397

There are three possible Visibilities:

  1. Visible
  2. Hidden
  3. Collapsed

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

Upvotes: 1

Related Questions