customized StringFormat in 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##}'}"
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.
精彩评论