Reputation: 12880
I'm new to WPF and trying to mash together some concepts I'm reading about.
What I'm trying to do is a build a localizable UI. For simplicity, let's say I am building a UI with string: "The file takes up 2 GB in disk space."
The "2 GB" portion is dynamic. The value could change depending upon the file the user selects. Secondly, a conversion should take from ulong (file size bytes) to string (friendly size, using appropriate units e.g. KB, MB, GB, TB, etc.).
I was thinking an IValueConverter
would be most appropriate for the byte count to friendly-file-size conversion. I was also thinking that I'd store "The file takes up {0} in disk space." as a string resource.
I'm not sure the IValueConverter
will be of use here. Can it be used with String.Format()
? I don't see how it could be used in a binding directly, because we're inserting the conversion result into the localizable text template.
Is there a better way to approach this?
Upvotes: 0
Views: 442
Reputation: 1307
Use this handy bytes name to text converter and an 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.");
}
}
Upvotes: 1
Reputation: 184376
Bindings have a StringFormat
property, you should be able to use that if you can somehow reference your localized string (possibly using a custom markup extension).
Upvotes: 1