Introduction:
Generally we need to set Visibility property for WPF control based on bit (True/False) value from database. The following snippet shows how to convert bool value to Visibility and vice-versa using System.Windows.Data.IValueConverter interface .
WPF control uses Visibility attribute to show/hide/collapse the control. Visibility is an enumeration from System.Windows namespace.
Visibility enumeration values are
- Visible - To display control.
- Collapsed - Do not display the control and do not reserve space for it in the layout.
- Hidden - Do not display the control, but reserve space for the control in the layout.
Note: Mostly we use Visible/Collapsed values so following example converts True to Visible and False to Collapsed. If you want to change False to Hidden just change Visibility.Collapsed to Visibility.Hidden in Convert method.
VisibilityConverter.cs:
using System.Windows;
using System.Windows.Data;
namespace DotNetMirror.Converters
{
public class VisibilityConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool visibility = false;
if (value is bool)
{
visibility = (bool)value;
}
return visibility ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Visibility visibility = (Visibility)value;
return (visibility == Visibility.Visible);
}
}
}
XAML:
<Window
xmlns:converter="clr-namespace:DotNetMirror.Converters"
</Window>
<Window.Resources>
<converter:VisibilityConverter x:Key="VisibilityConverter" />
</Window.Resources>
<Label Content="VisibilityConverter" Visibility="{ Binding IsVisible, Converter={StaticResource VisibilityConverter}}" />
Binding IsVisible - Bool value from DataContext.