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##}'}"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With