我是WPF的新手,并尝试将我正在阅读的一些概念混合在一起。
我要做的是构建一个可本地化的UI。为简单起见,假设我正在使用字符串构建UI:“该文件在磁盘空间中占用2 GB。”
“2 GB”部分是动态的。值可能会根据用户选择的文件而更改。其次,转换应该从ulong(文件大小字节)到字符串(友好大小,使用适当的单位,例如KB,MB,GB,TB等)。
我认为IValueConverter
最适合字节数到友好文件大小的转换。我还在想我会存储“文件在磁盘空间中占用{0}。”作为字符串资源。
我不确定IValueConverter
会在这里使用。可以与String.Format()
一起使用吗?我没有看到如何直接在绑定中使用它,因为我们将转换结果插入到可本地化的文本模板中。
有没有更好的方法来解决这个问题?
答案 0 :(得分:1)
绑定有StringFormat
property,如果你能以某种方式引用你的本地化字符串(可能使用自定义markup extension),你应该可以使用它。
答案 1 :(得分:1)
将此方便的字节名称用于文本转换器和IValueConverter
private string formatBytes(float bytes)
{
string[] Suffix = { "B", "KB", "MB", "GB", "TB" };
int i;
double dblSByte=0;
for (i = 0; (int)(bytes / 1024) > 0; i++, bytes /= 1024)
dblSByte = bytes / 1024.0;
return String.Format("{0:0.00} {1}", dblSByte, Suffix[i]);
}
public class BytesSuffixConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
float bytes = (float)value;
return formatBytes(bytes);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new Exception("Not Supported.");
}
}