6
在DataGrid中設置列的自定義格式的最有效方法是什麼?我無法使用下面的StringFormat,因爲我的複雜格式也取決於此ViewModel的其他屬性。 (例如價格格式有基於不同市場的一些複雜格式的邏輯。)在WPF DataGrid中自定義StringFormat
Binding ="{Binding Price, StringFormat='{}{0:#,##0.0##}'}"
在DataGrid中設置列的自定義格式的最有效方法是什麼?我無法使用下面的StringFormat,因爲我的複雜格式也取決於此ViewModel的其他屬性。 (例如價格格式有基於不同市場的一些複雜格式的邏輯。)在WPF DataGrid中自定義StringFormat
Binding ="{Binding Price, StringFormat='{}{0:#,##0.0##}'}"
你可以使用一個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();
}
}
現在地結合您的視圖模型屬性和格式同樣的事情:
<MultiBinding Converter="{StaticResource formatter}">
<Binding Path="Price" />
<Binding Path="PriceFormat" />
</MultiBinding>
關於這個的好處部分應該如何格式化價格的邏輯可以存在於ViewModel中並且是可測試的。否則,您可以將該邏輯移入轉換器並通過其所需的任何其他屬性。
這是優雅的,從來沒有使用多綁定之前,似乎是一個更好的解決方案複雜的格式比轉換器參數。 – 2010-05-19 01:45:18
當然,沒有什麼能阻止@Boris在他的ViewModel上簡單地實現一個「FormattedPrice」屬性並綁定到它。如果不那麼靈活,這將更容易。 – 2010-05-19 01:49:38
謝謝!有用!擁有「FormattedPrice」會更容易但不太優雅。我的數據網格中至少有10個不同的價格。我唯一擔心的是IMultiValueConverter的性能影響。 – 2010-05-19 02:15:31