Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF format displayed text?

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();
    }
}
like image 269
mpen Avatar asked May 06 '10 23:05

mpen


1 Answers

You can try using StringFormat in your binding expression if you're using .NET 3.5SP1 or later. See this post on Lester's WPF Blog or this post at Vince Sibal's blog for some syntax examples. The addition of StringFormat to bindings will eliminate most needs for Value Converters and conveniently keep your formatting with your markup rather than off in another class somewhere. It's certainly a lot less typing, too.

Maybe something like this will work:

<DataGridTextColumn
  Binding="{Binding Path=FileSizeBytes, Mode=OneWay, StringFormat='\{0:N0\} bytes'}"
  Header="Size" IsReadOnly="True" />

I'm not sure if clicking on the header to sort the items will sort them as strings or as the underlying data type, though, so depending on what your formatting expression looks like, you may or may not get the desired sorting behavior.

like image 138
Tim Trout Avatar answered Oct 20 '22 17:10

Tim Trout