Wednesday, December 4, 2013

Multi Value Converters

I find myself with a requirement to calculate a field in a grid as the product of two other fields in the same row. I have an editable quantity field and an editable unit price field. I also have a read-only field called Extended Price which is the product of the quantity and unit price fields. One way to do this is with a Multi Value Converter. This is simply a class that implements IMultiValueConverter. The Convert method takes a list of values instead of a single value. It's also declared differently in the XAML. Here's an example of the XAML that hooks my ExtPrice column into the Quantity and UnitPrice columns.

<datagridtextcolumn binding="{Binding Path=ExtPrice, Mode=OneWay}" elementstyle="{StaticResource RightAlign}" header="Ext. Price" isreadonly="true" width="80">
    <multibinding converter="{StaticResource ExtPriceConverter}" mode="OneWay" updatesourcetrigger="LostFocus">
        <binding path="QuantityOrdered"/>
        <binding path="UnitPrice"/>
        <binding stringformat="{}{0:0.00}"/>
    </multibinding > 
</datagridtextcolumn>

Each of the <Binding Path= declarations is evaluated at added to the values collection passed to the converter. It simply expects two numbers, multiplies them, and returns the product as a currency field The converter code is below.

Public Class ExtPriceConverter
    Implements IMultiValueConverter

    Public Function Convert(values() As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IMultiValueConverter.Convert

        Try
            If values.Length >= 2 AndAlso IsNumeric(values(0)) AndAlso IsNumeric(values(1)) Then
                Return String.Format(values(0) * values(1), "C")
            Else
                Return ""
            End If
        Catch ex As Exception
            Throw New Exception("ExtPriceConverter:" & ex.Message)
        End Try

    End Function

    Public Function ConvertBack(value As Object, targetTypes() As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object() Implements System.Windows.Data.IMultiValueConverter.ConvertBack
        Throw New NotSupportedException("Not Supported")
    End Function
End Class

No comments:

Post a Comment