WPF: how to use 2 converters in 1 binding?

Natrium picture Natrium · Oct 20, 2009 · Viewed 31.1k times · Source

I have a control that I want to show/hide, depending on the value of a boolean.

I have a NegatedBooleanConverter (switches true to false and vice versa) and I need to run this converter first. I have a BooleanToVisibilityConverter and I need to run this converter after the NegatedBoolConverter.

How can I fix this problem? I want to do this in XAML.

edit: this is a possible solution.

That doesn't seem to work. It first converts the value with the separate converters and then does something with the converted values.

What I need is:

  • Convert the value with the first converter (this gives convertedValue).
  • Convert convertedValue with the second converter and it's this result that I need.

Answer

Natrium picture Natrium · Oct 20, 2009

This is what I did:

public class CombiningConverter : IValueConverter
{
    public IValueConverter Converter1 { get; set; }
    public IValueConverter Converter2 { get; set; }

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        object convertedValue = Converter1.Convert(value, targetType, parameter, culture);
        return Converter2.Convert(convertedValue, targetType, parameter, culture);
    }

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

    #endregion
}

and I call it like this:

<converters:CombiningConverter x:Key="negatedBoolToVisibilityConverter" Converter1="{StaticResource NegatedBooleanConverter}" Converter2="{StaticResource BoolToVisibilityConverter}" />

A MultiValueConverter might also be possible I think. Maybe I'll try that later.