If you have ever had to bind a controls Visibility property to a boolean value, you have probably used Microsoft's built in
BooleanToVisibilityConverter
. The only problem with this is that you can only use it to convert
True
boolean values to
Visibility.Collapsed
. If you want it any other way, you need to provide your own
Converter
. In any major application, you always tended to end up with 4 different converters to do one simple job.
- Convert
True
values to Collapsed
- Convert
False
values to Collapsed
- Convert
True
values to Hidden
- Convert
False
values to Hidden
So I decided to create one converter that does all four jobs, and I thought I would share it.
The converter class:
public class BooleanToVisibilityConverter : IValueConverter
{
private bool triggerValue = false;
public bool TriggerValue
{
get { return triggerValue; }
set { triggerValue = value; }
}
private bool isHidden;
public bool IsHidden
{
get { return isHidden; }
set { isHidden = value; }
}
private object GetVisibility(object value)
{
if (!(value is bool))
return DependencyProperty.UnsetValue;
bool objValue = (bool)value;
if ((objValue && TriggerValue && IsHidden) || (!objValue && !TriggerValue && IsHidden))
{
return Visibility.Hidden;
}
if((objValue && TriggerValue && !IsHidden) || (!objValue && !TriggerValue && !IsHidden))
{
return Visibility.Collapsed;
}
return Visibility.Visible;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return GetVisibility(value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Usage:
<local:BooleanToVisibilityConverter x:Key="HiddenIfTrue" TriggerValue="True" IsHidden="True"/>
<local:BooleanToVisibilityConverter x:Key="HiddenIfFalse" TriggerValue="False" IsHidden="True"/>
<local:BooleanToVisibilityConverter x:Key="CollapsedIfTrue" TriggerValue="True" IsHidden="False"/>
<local:BooleanToVisibilityConverter x:Key="CollapsedIfFalse" TriggerValue="False" IsHidden="False"/>
If the boolean value you are using to bind to is a nullable type, then it will return a
DependancyProperty.UnsetValue
if the value returns
null
, and will set the control to
Visible
.
That's it. I hope you find this as useful as I did.