tags:

views:

152

answers:

1

What would be the most efficient way to set customized formatting of the column in DataGrid? I can't use the following StringFormat, as my sophisticated formatting also depends on some other property of this ViewModel. (e.g Price formatting has some complicated formatting logic based on different markets.)

Binding ="{Binding Price, StringFormat='{}{0:#,##0.0##}'}"
+2  A: 

You could use a MultiBinding with a converter. First define an IMultiValueConverter that formats the first value using the format specified in the second:

public class FormatConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // some error checking for values.Length etc
        return String.Format(values[1].ToString(), values[0]);
    }

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

Now bind both your ViewModel property and the format to the same thing:

<MultiBinding Converter="{StaticResource formatter}">
    <Binding Path="Price" />
    <Binding Path="PriceFormat" />
</MultiBinding>

The nice part about this is that the logic for how Price should be formatted can live in the ViewModel and be testable. Otherwise you could move that logic into the converter and pass in any other properties that it needed.

Matt Hamilton
That's elegant, never used Multi bindings before, seems like a much better solution to complex formatting than converter parameter.
Igor Zevaka
And of course there's nothing stopping @Boris from simply implementing a "FormattedPrice" property on his ViewModel and binding to that. That would be even easier if not as flexible.
Matt Hamilton
@Matt, thanks! It works! Having "FormattedPrice" would be easier but less elegant. I've got at least 10 different prices in my datagrid. My only concern at this stage is performance implications of IMultiValueConverter.
Boris Lipschitz
@Boris I've used IMultiValueConverters fairly heavily in several projects and they don't seem to affect performance in any noticeable way.
Matt Hamilton