BoolToVisibilityConverter - canton7/Stylet GitHub Wiki
In almost every project I've needed to hide/show an element based on some bool value in the ViewModel. You can do this with DataTriggers, or using a converter.
The converter implementation is very simple: when bound to a bool property, if it reads a true value, it returns one (preconfigured) visibility, if it reads a false value, it returns another.
If you bind in to a property of a type other than bool, it will use the following rules:
- If the value is null, it's treated as false
- If the value is 0 (as an int, float, double, etc), it's treated as false
- If the value is an empty collection, dictionary, etc, it's treated as false
- Otherwise, it's treated as true
This matches the truthsy/falsy rules seen in many languages. It's also handy if, say, you want to show a ListView
if and only if the collection it's bound to isn't empty.
Basic example usage:
<!-- In any .Resources section - doesn't have to be Window.Resources -->
<Window.Resources>
<s:BoolToVisibilityConverter x:Key="boolToVisConverter" TrueVisibility="Visible" FalseVisibility="Hidden"/>
</Window.Resources>
<!-- Later in code -->
<TextBlock Visibility="{Binding SomeBoolProperty, Converter={StaticResource boolToVisConverter}}"/>
If you want the (usual) case of a converter which uses Visiblity.Visible
for the true case, and Visibility.Collapsed
for the false case, there's a shortcut:
<TextBlock Visibility="{Binding SomeBoolProperty, Converter={x:Static s:BoolToVisibilityConverter.Instance}}"/>
Likewise, if you want the (slightly less usual) case of Visibility.Collapsed
for the true case and Visibility.Visible
for the false case, there's a similar shortcut:
<TextBlock Visibility="{Binding SomeBoolProperty, Converter={x:Static s:BoolToVisibilityConverter.InverseInstance}}"/>