Five minute recipe for a decent BoolToVisibilityConverter

There are a bunch of IValueConverters that WPF probably should ship with... MultiplyConverter, AdditionConverter etc. Rather oddly it does ship with one: The BooleanToVisibilityConverter:

However, I'm not a huge fan of the implementation as it gives me little control over what true and false actually map to. For example, should false be Collapsed or Visible? What if I want to invert? For these reasons I always craft my own (I really must start a codeplex project at some point to keep all these converters). Here it is:

public class BoolToVisibilityConverter : MarkupExtension, IValueConverter
{
public BoolToVisibilityConverter()
{
TrueValue = Visibility.Visible;
FalseValue = Visibility.Collapsed;
}

public Visibility TrueValue { get; set; }
public Visibility FalseValue { get; set; }

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool val = System.Convert.ToBoolean(value);
return val ? TrueValue : FalseValue;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return TrueValue.Equals(value) ? true : false;
}

public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}

As discussed in a previous post, I've used my Converters as MarkupExtensions tip but I've also made the TrueValue and FalseValue completely configurable so there's a clear route for both inversion and choice between Collapsed and Hidden. In fact, you could even have True==Collapsed and False==Hidden if you liked - not sure what you'd use that for though. Note that we set sensible defaults in the constructor.

Here's how to use it:

<StackPanel VerticalAlignment="Bottom">
<StackPanel.Resources>
<local:BoolToVisibilityConverter FalseValue="Collapsed" x:Key="btvc" />
</StackPanel.Resources>
<CheckBox x:Name="HideOrShowCheck">Hide or show the text...</CheckBox>
<TextBlock Text="Hello World!" Visibility="{Binding ElementName=HideOrShowCheck, Path=IsChecked,Converter={StaticResource btvc}}" />
</StackPanel>

Or, my preferred way:

<StackPanel VerticalAlignment="Bottom">
<CheckBox x:Name="HideOrShowCheck">Hide or show the text...</CheckBox>
<TextBlock Text="Hello World!" Visibility="{Binding ElementName=HideOrShowCheck, Path=IsChecked,Converter={local:BoolToVisibilityConverter FalseValue=Collapsed}}" />
</StackPanel>

Happy converting.

 

 

Originally posted by Josh Twist on 12 October 2009 here.