Over a million developers have joined DZone.

Goodbye BooleanToVisibilityConverter, welcome IsVisible!

DZone 's Guide to

Goodbye BooleanToVisibilityConverter, welcome IsVisible!

· ·
Free Resource

One can argue that BooleanToVisibilityConverter is rooted deeply in the XAML-based platforms. It is the simplest IValueConverter one can implement and you can find it implemented in various toolkits, frameworks or simply reimplemented time and time again by developers. Part of the reason is that the default facility for showing and hiding is unbindable to regular boolean property.

Historical reason for this can be found in WPF where controls can be in one of the three following states: Visible, Hidden, and Collapsed. When Silverlight was introduced, the Hidden state was removed and only two possibilities existed and which correspond to boolean states.

However, the syntax is atrocious. Look at the following example:

Visibility={Binding IsVisible,
                    Converter={StaticResource BooleanToVisibilityConverter}}

Imagine writing that every time you need to hide a control? Well, you just imagined a lot of code out there.

So, how can we fix this and shorten the syntax? By using attached properties of course. Even though there is no such thing as an IsVisible property, it doesn’t mean we cannot invent one ourselves. The final syntax appears similar to this one:

common:Alt.IsVisible={Binding IsVisible}

Isn’t that much readable? Both the namespace and the owner class names can be shortened to get an even shorter syntax.

Here is the implementation:

/// <summary>
/// Definition of alternative attached properties for various
/// controls.
/// </summary>
public static class Alt
	public static readonly DependencyProperty IsVisibleProperty = DependencyProperty.RegisterAttached(
		"IsVisible", typeof(bool?), typeof(Alt), new PropertyMetadata(default(bool?), IsVisibleChangedCallback));

	private static void IsVisibleChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		var fe = d as FrameworkElement;
		if (fe == null)

		fe.Visibility = ((bool?)e.NewValue) == true
			? Visibility.Visible
			: Visibility.Collapsed;

	public static void SetIsVisible(DependencyObject element, bool? value)
		element.SetValue(IsVisibleProperty, value);

	public static bool? GetIsVisible(DependencyObject element)
		return (bool?)element.GetValue(IsVisibleProperty);

The source code and the accompanying sample project can also be found on the Github repository here: github.com/MassivePixel/wp-common.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}