Skip to content

Instantly share code, notes, and snippets.

@idiotandrobot
Created July 31, 2014 19:26
Show Gist options
  • Save idiotandrobot/9c14b2aa2e0a6b5ec959 to your computer and use it in GitHub Desktop.
Save idiotandrobot/9c14b2aa2e0a6b5ec959 to your computer and use it in GitHub Desktop.
Bool to Visibility converters
public class BoolToInvisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isInvisible = (bool)value;
if (BoolToVisibilityConverter.IsVisibilityInverted(parameter))
isInvisible = !isInvisible;
return (isInvisible ? Visibility.Collapsed : Visibility.Visible);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isInvisible = ((Visibility)value == Visibility.Collapsed);
if (BoolToVisibilityConverter.IsVisibilityInverted(parameter))
isInvisible = !isInvisible;
return isInvisible;
}
}
public class BoolToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isVisible = (bool)value;
if (IsVisibilityInverted(parameter))
isVisible = !isVisible;
return (isVisible ? Visibility.Visible : Visibility.Collapsed);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isVisible = ((Visibility)value == Visibility.Visible);
if (IsVisibilityInverted(parameter))
isVisible = !isVisible;
return isVisible;
}
internal static bool IsVisibilityInverted(object parameter)
{
return (GetVisibilityMode(parameter) == Visibility.Collapsed);
}
internal static Visibility GetVisibilityMode(object parameter)
{
Visibility mode = Visibility.Visible;
if (parameter != null)
{
if (parameter is Visibility)
{
mode = (Visibility)parameter;
}
else
{
try
{
mode = (Visibility)Enum.Parse(typeof(Visibility), parameter.ToString(), true);
}
catch (FormatException ex)
{
throw new FormatException("Invalid Visibility specified as the ConverterParameter. Use Visible or Collapsed.", ex);
}
}
}
return mode;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment