Quantcast
Channel: Infragistics Community
Viewing all articles
Browse latest Browse all 2374

A Silverlight BooleanToVisibilityConverter

$
0
0

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:

publicclassBooleanToVisibilityConverter : IValueConverter
{
    publicobject Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool bValue = false;
        if (value isbool)
        {
            bValue = (bool)value;
        }
        elseif (value isNullable<bool>)
        {
            Nullable<bool> tmp = (Nullable<bool>)value;
            bValue = tmp.HasValue ? tmp.Value : false;
        }
        return (bValue) ? Visibility.Visible : Visibility.Collapsed;
    }

    publicobject ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value isVisibility)
        {
            return (Visibility)value == Visibility.Visible;
        }
        else
        {
            returnfalse;
        }
    }
}

Usage:

<Grid.Resources>
    <converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</Grid.Resources>

<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!


Viewing all articles
Browse latest Browse all 2374

Trending Articles