Custom StringFormat in WPF DataGrid

What would be the most efficient way to set custom column formatting in a DataGrid? I cannot use the following StringFormat, since my complex formatting also depends on another property of this ViewModel. (for example, price formatting has some complicated formatting logic in different markets.)

Binding ="{Binding Price, StringFormat='{}{0:#,##0.0##}'}" 
+6
c # wpf datagrid
source share
1 answer

You can use 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 the ViewModel properties and the format to the same:

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

The nice part of this is that the logic of how Price should be formatted can live in the ViewModel and be testable. Otherwise, you could move this logic to the converter and pass any other properties they need.

+6
source share

All Articles