A Silverlight BooleanToVisibilityConverter

Brian Lagunas / Thursday, January 31, 2013

Here is my Silverlight BooleanToVisibilityConverter.  I know this is a very common and simple converter that every Silverlight developer has in their toolbox.  It’s not a new concept or groundbreaking tip, and a quick Google/Bing search will find you many flavors of its’ implementation.  So why post it now?  Especially given the current state of Silverlight?  Well, as you all know, Silverlight isn’t getting much love (no love really) these days, but Silverlight development is still happening. 

What did you say Brian?  Yes, believe it or not, Silverlight code is still being written (GASP!).  So I figured I will show Silverlight a little love, and share a little piece of my code base with the world.  I am simply sharing an implementation of a BooleanToVisibilityConverter that I use in my Silverlight applications.  It’s nothing fancy, and I am probably posting this more for me than the community.  I use this so often, I need an easily accessible place to keep it so that it is easy to find.  No more opening past projects and solutions and digging through a code base to get it.  A simple search on my blog will bring it to my fingertips.

Here’s the code: (UPDATED: based on the feedback in the comments section, I have updated the implementation)

public class BooleanToVisibilityConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        return (value as bool? == true) ? Visibility.Visible : Visibility.Collapsed;

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        if (value is Visibility)
            return (Visibility)value == Visibility.Visible;
            return false;


    <converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />

<ToggleButton Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}"/>

Note:  The “converters” namespace has been declared at the top of my view and points to the location of the converter in my application.

Maybe this simple converter can be useful for you.  If not, then hopefully you didn’t waste your time by reading the entire post.

I am still amazed that this simple converter never made it into the Silverlight code base.  Go figure!