Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF IValueConverter - converting multiple values into a single value

I'm trying to maintain someone else's code right now where that person is a WPF expert. I, on the other hand, am not. :)

The code uses the IValueConverter to convert a state enumeration into a boolean which governs whether or not a UserControl is displayed on the screen.

I've discovered a shortcoming that a single enumeration in this circumstance is not enough, there's actually another boolean that needs to be considered as well. Is there another object that could be used that would take 2 items in as arguments in order to do a conversion? (The "converter" parameter is already being used.)

A quick example would be the following.

The logic of the existing code says...

If it's sunny, go to work.
If it's raining, don't go to work.

I need to take another thing into account which would make it as follows.

If it's sunny and you're wearing pants, go to work.
If it's sunny and you're not wearing pants, don't go to work.
If it's raining and you're wearing pants, don't go to work.
If it's raining and you're not wearing pants, don't go to work.

IValueConverter, which would perform the conversion only allows me to take one "thing" in for conversion.

Any help is appreciated. Thanks,

mj

like image 692
mj_ Avatar asked Dec 10 '22 13:12

mj_


1 Answers

Use an IMultiValueConverter

public class MyMultiValueConverter: IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // Do something with the values array. It will contain your parameters
    }

    public object[] ConvertBack(object values, Type[] targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

You also need to use a MultiBinding in the XAML instead of a regular binding

<MultiBinding Converter="{StaticResource MyMultiValueConverterKey}">
    <Binding Path="Value1" />
    <Binding Path="Value2" />
</MultiBinding>
like image 196
Rachel Avatar answered Jan 02 '23 19:01

Rachel