I have a column defined like this:
<DataGridTextColumn Binding="{Binding Path=FileSizeBytes, Mode=OneWay}" Header="Size" IsReadOnly="True" />
But instead of displaying the file size as a big number, I’d like to display units, but still have it sort by the actual FileSizeBytes. Is there some way I can run it through a function or something before displaying it?
@Igor:
Works great.
http://img200.imageshack.us/img200/4717/imageget.jpg
[ValueConversion(typeof(long), typeof(string))]
class FileSizeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string[] units = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
double size = (long)value;
int unit = 0;
while (size >= 1024)
{
size /= 1024;
++unit;
}
return String.Format("{0:0.#} {1}", size, units[unit]);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Binding to a function is possible in WPF, but it’s generally painful. In this case a more elegant approach would be to create another property which returns a formatted string and bind to that.
In XAML, bind to
FileSizeFormatted:EDIT Alternative solution, thanks to Charlie for pointing this out.
You could write your own value converter by implementing
IValueConverter.Then in XAML: