我只想将文件大小转换为字符串格式,如“1 MB”或“2.5 GB”,我认为我从Q.42 库中引用了转换器,我的 XAML 代码可能有错误,请帮我弄清楚这一点。
主页.XAML
<Page.Resources>
<local:ByteToStringConverter x:Key="BytesToString" />
</Page.Resources>
<Grid>
<TextBlock Text="{Binding Path=Size, Converter={StaticResource BytesToString}}"/>
</Grid>
MainPage.XAML.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
StorageFile f = await KnownFolders.MusicLibrary.GetFileAsync("video.mp4");
BasicProperties bs = await f.GetBasicPropertiesAsync();
MyClass obj = new MyClass();
obj.Size = bs.Size;
}
}
public class MyClass : INotifyPropertyChanged
{
private ulong _Size;
public ulong Size
{
get { return _Size; }
set { _Size = value; OnPropertyChanged("Size");}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
ByteToStringConverter.cs
public class ByteToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string size = "0 KB";
if (value != null)
{
double byteCount = 0;
byteCount = System.Convert.ToDouble(value);
if (byteCount >= 1073741824)
size = String.Format("{0:##.##}", byteCount / 1073741824) + " GB";
else if (byteCount >= 1048576)
size = String.Format("{0:##.##}", byteCount / 1048576) + " MB";
else if (byteCount >= 1024)
size = String.Format("{0:##.##}", byteCount / 1024) + " KB";
else if (byteCount > 0 && byteCount < 1024)
size = "1 KB"; //Bytes are unimportant ;)
}
return size;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}