WPF DataGrid中的自定义StringFormat

Bor*_*itz 6 c# wpf datagrid

在DataGrid中设置列的自定义格式的最有效方法是什么?我不能使用以下StringFormat,因为我复杂的格式也依赖于此ViewModel的其他一些属性.(例如,价格格式有一些基于不同市场的复杂格式逻辑.)

Binding ="{Binding Price, StringFormat='{}{0:#,##0.0##}'}"
Run Code Online (Sandbox Code Playgroud)

Mat*_*ton 6

您可以将MultiBinding与转换器一起使用.首先定义一个IMultiValueConverter,它使用第二个值中指定的格式格式化第一个值:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在将您的ViewModel属性和格式绑定到同一个东西:

<MultiBinding Converter="{StaticResource formatter}">
    <Binding Path="Price" />
    <Binding Path="PriceFormat" />
</MultiBinding>
Run Code Online (Sandbox Code Playgroud)

关于这一点的好处是,应该如何格式化Price的逻辑可以存在于ViewModel中并且是可测试的.否则,您可以将该逻辑移动到转换器中并传入其所需的任何其他属性.