A Generic Boolean Value Converter
- by codingbloke
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:- BoolToValueConverter using System; 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:- Value Converters using System; 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:BoolToBrushConverter x:Key="Highlighter" FalseValue="Transparent" TrueValue="Yellow" /> <local:BoolToStringConverter x:Key="CYesNo" FalseValue="No" TrueValue="Yes" /> <local:BoolToVisibilityConverter x:Key="InverseVisibility" TrueValue="Collapsed" FalseValue="Visible" />