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.

[ContentProperty("Converters")]
public class ComposingConverter : IValueConverter
{
    private readonly Collection<IValueConverter> _converters = new Collection<IValueConverter>();
 
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public Collection<IValueConverter> Converters
    {
        get { return _converters; }
    }
 
    public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
    {
        for (int i = 0; i < _converters.Count; i++)
        {
            value = _converters[i].Convert(value, targetType, parameter, culture);
        }
 
        return value;
    }
 
    public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
    {
        for (int i = _converters.Count - 1; i >= 0; i--)
        {
            value = _converters[i].ConvertBack(value, targetType, parameter, culture);
        }
 
        return value;
    }
}

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

<data:ComposingConverter x:Key="BooleanToVisibilityInverseConverter">
    <data:NotConverter />
    <data:BooleanToVisibilityConverter />
</data:ComposingConverter>

Elegant solution, don’t you think?


Would you like to get the most interesting content about C# every Monday?
Sign up to C# Digest and stay up to date!