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
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 to share