Click here to Skip to main content
15,881,248 members
Articles / Desktop Programming / WPF
Tip/Trick

All purpose Boolean to Visibility Converter

Rate me:
Please Sign up or sign in to vote.
4.80/5 (10 votes)
20 Nov 2011CPOL 55.9K   9   4
All purpose Boolean to Visibility Converter
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.

  1. Convert True values to Collapsed
  2. Convert False values to Collapsed
  3. Convert True values to Hidden
  4. 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:
C#
/// <summary>
    /// Converts Boolean Values to Control.Visibility values
    /// </summary>
    public class BooleanToVisibilityConverter : IValueConverter
    {
        //Set to true if you want to show control when boolean value is true
        //Set to false if you want to hide/collapse control when value is true
        private bool triggerValue = false;
        public bool TriggerValue
        {
            get { return triggerValue; }
            set { triggerValue = value; }
        }
        //Set to true if you just want to hide the control
        //else set to false if you want to collapse the control
        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:
XML
<!--Hides control if boolean value is true-->
               <local:BooleanToVisibilityConverter x:Key="HiddenIfTrue" TriggerValue="True" IsHidden="True"/>
               <!--Hides control if boolean value is false-->
               <local:BooleanToVisibilityConverter x:Key="HiddenIfFalse" TriggerValue="False" IsHidden="True"/>
               <!--Collapses control if boolean value is true-->
               <local:BooleanToVisibilityConverter x:Key="CollapsedIfTrue" TriggerValue="True" IsHidden="False"/>
               <!--Collapses control if boolean value is 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DynaByte Solutions
Zimbabwe Zimbabwe
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNice, best solution I have found that is reusable and makes sense. Pin
Andy Missico3-Mar-14 12:08
Andy Missico3-Mar-14 12:08 
AnswerRe: Nice, best solution I have found that is reusable and makes sense. Pin
Wayne Gaylard3-Mar-14 18:32
professionalWayne Gaylard3-Mar-14 18:32 
GeneralReason for my vote of 5 I am giving you a five because I did... Pin
Paulo Zemek17-Nov-11 5:18
mvaPaulo Zemek17-Nov-11 5:18 
Reason for my vote of 5
I am giving you a five because I didn't knew the BooleanToVisibilityConverter... also I think it is strange that true is hidden (as the name is visibility) and I liked that you allow all the possibilities for the boolean. I think that if the value is null you may use the other value between hidden or collapsed, so the user may use true, false or null.
GeneralRe: Thanks! Pin
Wayne Gaylard17-Nov-11 5:45
professionalWayne Gaylard17-Nov-11 5:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.