Wednesday, March 22, 2017

WPF Tip #5 - Data Binding with IMultiValueConverter

In Tip #4, we examined the use of IValueConverter with WPF binding. If you are using MulitBinding, a converter class that implements IMultiValueConverter is needed.

Like the IValueConverter, the class must implement Convert and ConvertBack methods. The difference being the multiple values come in as an object[] parameter in Convert() and go back out as an object[] return value in ConvertBack(). The following example takes two string values as input and returns them concatenated with a pipe '|'. It will convert them back using the Split function, assuming your text value contains no other pipes.

public class TextAppendMultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return String.Concat(values[0], "|", values[1]);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return (value as string).Split('|');
    }
}

This code will use the converter in a WPF TextBox's Text property MultiBinding.

<TextBox>
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource TextAppendMultiConverter}" FallbackValue="Busy loading...">
            <Binding Path="IntroText"/>
            <Binding Path="ContentText"/>
        </MultiBinding>
    </TextBox.Text>
</TextBox>

The FallbackValue will be displayed if the converter fails or data is unavailable in the attached DataContext.

Next time, we will shift gears away from data binding. Happy coding!

 

del.icio.us Tags: ,,

No comments:

Post a Comment