Wednesday, May 23, 2012

Versatile WPF Boolean to Visibility Converter

The BooleanToVisibilityConverter that cames with WPF has some weak points because it cannot handle Visibility.Hidden or it cannot work in 'inverse' mode.

Suppose you have two controls and you want only one of them to be visible based on some IsEditing dependency property. With the build in converter, there is no easy way for achieving this functionality.

The following BooleanToVisibilityConverter solves this issues:

To use it in the above scenario:


Now, when IsEditing is false, the text block is visible. When IsEditing is true, the text block becomes collapsed and the text box is visible.

If one needs to use the Visibility.Hidden value instead of Visibility.Collapsed, the FalseValue property on the BooleanToVisibilityConverter should be set to Visibility.Hidden.