65.9K
CodeProject is changing. Read more.
Home

All purpose Boolean to Visibility Converter

starIconstarIconstarIconstarIconstarIcon

5.00/5 (6 votes)

Nov 18, 2011

CPOL
viewsIcon

18191

I would first like to say that I have been through the same situation, but never took the time to develop a more dynamic converter. I like your idea, but don't like the implementation. If I know what I want to happen (when the value is true then make the control hidden), I have to do some mental...

I would first like to say that I have been through the same situation, but never took the time to develop a more dynamic converter. I like your idea, but don't like the implementation. If I know what I want to happen (when the value is true then make the control hidden), I have to do some mental translation to Boolean values (TriggerValue="True" IsHidden="True"). I think this solution is cleaner and more clear about what it is doing. Also, thanks to Paulo Zemek for recommending the null value.
/// <summary>
	/// Converts Boolean Values to Control.Visibility values
	/// </summary>
	public class BooleanToVisibilityConverter : IValueConverter
	{
		private Visibility valueWhenTrue = Visibility.Visible;
		public Visibility ValueWhenTrue
		{
			get { return valueWhenTrue; }
			set { valueWhenTrue = value; }
		}

		private Visibility valueWhenFalse = Visibility.Collapsed;
		public Visibility ValueWhenFalse
		{
			get { return valueWhenFalse; }
			set { valueWhenFalse = value; }
		}

		private Visibility valueWhenNull = Visibility.Hidden;
		public Visibility ValueWhenNull
		{
			get { return valueWhenNull; }
			set { valueWhenNull = value; }
		}

		private object GetVisibility(object value)
		{
			if (!(value is bool) || value == null)
				return ValueWhenNull;

			if ((bool)value)
				return valueWhenTrue;

			return valueWhenFalse;
		}

		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();
		}
	}
Using your examples:
<!--Hides control if boolean value is true-->
               <local:BooleanToVisibilityConverter x:Key="HiddenIfTrue" ValueWhenTrue="Hidden" ValueWhenFalse="Visible"/>
               <!--Hides control if boolean value is false-->
               <local:BooleanToVisibilityConverter x:Key="HiddenIfFalse" ValueWhenTrue="Visible" ValueWhenFalse="Hidden"/>
               <!--Collapses control if boolean value is true-->
               <local:BooleanToVisibilityConverter x:Key="CollapsedIfTrue" ValueWhenTrue="Collapsed" ValueWhenFalse="Visible"/>
               <!--Collapses control if boolean value is false-->
               <local:BooleanToVisibilityConverter x:Key="CollapsedIfFalse" ValueWhenTrue="Visible" ValueWhenFalse="Collapsed"/>