A Generic Boolean Value Converter
Posted
by codingbloke
on Geeks with Blogs
See other posts from Geeks with Blogs
or by codingbloke
Published on Fri, 28 May 2010 11:07:02 GMT
Indexed on
2010/05/28
12:12 UTC
Read the original article
Hit count: 375
On fairly regular intervals a question on Stackoverflow like this one: Silverlight Bind to inverse of boolean property value appears. The same answers also regularly appear. They all involve an implementation of IValueConverter and basically include the same boilerplate code.
The required output type sometimes varies, other examples that have passed by are Boolean to Brush and Boolean to String conversions. Yet the code remains pretty much the same. There is therefore a good case to create a generic Boolean to value converter to contain this common code and then just specialise it for use in Xaml. Here is the basic converter:-
using System.Windows.Data;
namespace SilverlightApplication1
{
public class BoolToValueConverter<T> : IValueConverter
{
public T FalseValue { get; set; }
public T TrueValue { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return FalseValue;
else
return (bool)value ? TrueValue : FalseValue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(TrueValue);
}
}
}
With this generic converter in place it easy to create a set of converters for various types. For example here are all the converters mentioned so far:-
using System.Windows;
using System.Windows.Media;
namespace SilverlightApplication1
{
public class BoolToStringConverter : BoolToValueConverter<String> { }
public class BoolToBrushConverter : BoolToValueConverter<Brush> { }
public class BoolToVisibilityConverter : BoolToValueConverter<Visibility> { }
public class BoolToObjectConverter : BoolToValueConverter<Object> { }
}
With the specialised converters created they can be specified in a Resources property on a user control like this:-
<local:BoolToStringConverter x:Key="CYesNo" FalseValue="No" TrueValue="Yes" />
<local:BoolToVisibilityConverter x:Key="InverseVisibility" TrueValue="Collapsed" FalseValue="Visible" />
© Geeks with Blogs or respective owner