Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

customized StringFormat in WPF DataGrid

Tags:

c#

wpf

datagrid

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##}'}"
like image 217
Boris Lipschitz Avatar asked May 19 '10 01:05

Boris Lipschitz


1 Answers

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.

like image 182
Matt Hamilton Avatar answered Sep 20 '22 10:09

Matt Hamilton