Saturday, March 13, 2010

Yet Another WPF Boolean Converter – or not! The only WPF Boolean Converter you need.

I sat down to write yet another WPF BooleanToXXX converter and decided this was not acceptable. Bool converters are used to select between two choices based on the true/false value of the bool in question. To me this cried out for a generic class to handle all of these cases so I created a class called BooleanToValueConverter as shown below.


public class BooleanToValueConverter : IValueConverter
{
// parameter specifies what to return based on the boolean
// parameter is of the format value1;value2 where value1 is returned if the bool is false and value2 is returned if the bool is true
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
System.Diagnostics.Debug.Assert(value is bool);
System.Diagnostics.Debug.Assert(parameter as string != null);
if (value == null || !(value is bool) || parameter as string == null)
return null;

string[] valueList = (parameter as string).Split(new char[] { ';' });
System.Diagnostics.Debug.Assert(valueList.Length == 2);
if (valueList.Length != 2)
return null;

if ((bool)value == true)
return valueList[1];

return valueList[0];
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

The following XAML snippets show how the converter is used. The trick to making this converter generic is the ConverterParameter which takes a string of two options separated by a semicolon. The converter parameter is of the format value1;value2 where value1 is returned if the bool is false and value2 is returned if the bool is true.


<Window.Resources>
<local:BooleanToValueConverter x:Key="booleanToValueConverter"/>
</Window.Resources>

<Button Content="_Delete" Visibility="{Binding Path=IsDeleteAllowed, Converter={StaticResource booleanToValueConverter}, ConverterParameter=Collapsed;Visible}" />

Now in the example screen shot below we see that the Delete button is not visible since the IsDeleteAllowed property is returning false and thus the button is collapsed.



I have used this in many locations to choose between two values including visibility as shown above, two margins, grid row/column widths, and more. The grid row use case is interesting because you can make a grid row disappear by binding to the row height and using a BooleanToValueConverter to set the width to 0 when you want the row to disappear.

The full code is available here. 

Enjoy!
Todd Stephan

No comments:

Post a Comment