DCSIMG
May 2010 - Posts - Technicals and Technicalities

Technicals and Technicalities

Ariel's uneditable Bliki

May 2010 - Posts

Build a Better BooleanToVisibilityConverter

I feel dirty whenever I use XOR in my code. Then I’m proud of myself and suppress any previous feelings which may indicate that I did something wrong.

Anyway, when WPFing and messing with visibility of items – the BooleanToVisibilityConverter is a very handy tool.  However, binding to a bool property means that you need the bool mean the same as the visibility, i.e. true for visible. If you need the opposite – you need to create an opposite property on the VM to bind to, or write an opposite converter.

No more.

   1: public class BoolToVisConverter : IValueConverter 
   2: { 
   3:     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
   4:     { 
   5:         return (bool)value ^ (parameter == null ? false : !bool.Parse((string)parameter)) ? Visibility.Visible : Visibility.Collapsed; 
   6:     } 
   7:
   8: }

Using a ConverterParameter in your binding expression you can just specify to negate the return value of the bound property.

Usage in XAML:

Visibility="{Binding IsInvalidState, Converter={StaticResource BoolToVisConverter}, ConverterParameter=false}"