gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:31:02 25 4
gpt4 key购买 nike

我有一个这样定义的列:

<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com