mpe*_*pen 6 c# wpf xaml .net-4.0
我有一个像这样定义的列:
<DataGridTextColumn Binding="{Binding Path=FileSizeBytes, Mode=OneWay}" Header="Size" IsReadOnly="True" />
Run Code Online (Sandbox Code Playgroud)
但是我没有将文件大小显示为一个大数字,而是想显示单位,但仍然按实际排序FileSizeBytes.有没有什么方法可以在显示之前通过函数或其他东西运行它?
@Igor:
效果很好.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
在 WPF 中可以绑定到函数,但通常很痛苦。在这种情况下,更优雅的方法是创建另一个返回格式化字符串并绑定到该字符串的属性。
class FileInfo {
public int FileSizeBytes {get;set;}
public int FileSizeFormatted {
get{
//Using general number format, will put commas between thousands in most locales.
return FileSizeBytes.ToString("G");
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 XAML 中,绑定到FileSizeFormatted:
<DataGridTextColumn Binding="{Binding Path=FileSizeBytes, Mode=OneWay}" Header="Size" IsReadOnly="True" />
Run Code Online (Sandbox Code Playgroud)
编辑替代解决方案,感谢查理指出这一点。
您可以通过实现来编写自己的值转换器IValueConverter。
[ValueConversion(typeof(int), typeof(string))]
public class IntConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
//needs more sanity checks to make sure the value is really int
//and that targetType is string
return ((int)value).ToString("G");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
//not implemented for now
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在 XAML 中:
<UserControl.Resources>
<src:DateConverter x:Key="intConverter"/>
</UserControl.Resources>
...
<DataGridTextColumn Binding="{Binding Path=FileSizeBytes, Mode=OneWay, Converter={StaticResource intConverter}}" Header="Size" IsReadOnly="True" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4802 次 |
| 最近记录: |