Jakub Chodounský

Composing Converters Together in WPF

Did you ever need combining multiple data converters in WPF? And why would you do such thing?

I often use BoolToVisibilityConverter. Its purpose is pretty straighforward. True value is converted to Visibility.Visible and false is converted to Visibility.Collapsed. But what if I need the oposite functionality, should I write another converter and call it BoolToVisibilityInverseConverter? If I had already written a NotConverter isn’t it a waste of time to do that?

The answer is yes and the solution is to combine these converters together using a composing converter.

 1[ContentProperty("Converters")]
 2public class ComposingConverter : IValueConverter
 3{
 4    private readonly Collection<IValueConverter> _converters = new Collection<IValueConverter>();
 5 
 6    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
 7    public Collection<IValueConverter> Converters
 8    {
 9        get { return _converters; }
10    }
11 
12    public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
13    {
14        for (int i = 0; i < _converters.Count; i++)
15        {
16            value = _converters[i].Convert(value, targetType, parameter, culture);
17        }
18 
19        return value;
20    }
21 
22    public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
23    {
24        for (int i = _converters.Count - 1; i >= 0; i--)
25        {
26            value = _converters[i].ConvertBack(value, targetType, parameter, culture);
27        }
28 
29        return value;
30    }
31}

The usage in XAML is very simple and is ilustrated in the example belove.

1<data:ComposingConverter x:Key="BooleanToVisibilityInverseConverter">
2    <data:NotConverter />
3    <data:BooleanToVisibilityConverter />
4</data:ComposingConverter>

Elegant solution, don’t you think?