c# - WPF格式显示的文字?

标签 c# wpf xaml .net-4.0

我有一个这样定义的列:

<DataGridTextColumn Binding="{Binding Path=FileSizeBytes, Mode=OneWay}" Header="Size" IsReadOnly="True" />

但是我不想将文件大小显示为一个大数字,而是想显示单位,但仍按实际 FileSizeBytes 对其进行排序。有什么方法可以在显示之前通过函数或其他方式运行它吗?


@伊戈尔:

效果很好。

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();
    }
}

最佳答案

如果您使用的是 .NET 3.5SP1 或更高版本,则可以尝试在绑定(bind)表达式中使用 StringFormat。参见 this post on Lester's WPF Blogthis post at Vince Sibal's blog对于一些语法示例。将 StringFormat 添加到绑定(bind)将消除对值转换器的大部分需求,并方便地使用标记保留格式,而不是在某个地方的另一个类中关闭。当然,打字也少了很多。

也许这样的事情会奏效:

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

不过,我不确定单击标题对项目进行排序是否会将它们排序为字符串或基础数据类型,因此根据您的格式化表达式的外观,您可能会或可能不会获得所需的排序行为。

关于c# - WPF格式显示的文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2785097/

相关文章:

c# - 获取行中值计数 > 1 的不同行?

c# - 需要比 XML 更简单的数据源

c# - System.Drawing.SystemColors 的默认值

WPF文本 block ,前景色的混合

c# - 使用 LINQ2SQL DataContext 表作为其 ItemsSource 时使用 DataGrid 的正确方法(最佳实践)

c# - 如何将用户控件作为 ListBoxItem

c# - Excel 互操作 : Can you listen for a change in range value?

c# - 在 Visual Studio 中创建 WPF UI 的建议

c# - xaml 中的 MouseBinding 手势字符串

c# - 获取面板中的鼠标位置(当鼠标悬停在另一个UIElement上时)到ViewModel