我只想文件大小轉換成字符串格式,如「1 MB」或「2.5 GB」,我稱之爲轉換器從Q.42 library我想,我的XAML代碼可能有錯誤,請幫我弄清楚這一點。沒能獲得文件大小在字符串字節字符串轉換器在C#/ XAML Metro應用
MainPage.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();
}
}
數據仍然沒有得到與文本塊綁定,我試圖消除器 – Xyroid
什麼是'DataContext'設置?嘗試將其設置爲頁面本身。 – akton
誰是DataContext?我用'this.DataContext = this'在MainPage.xaml.cs中嘗試過,但不工作。 – Xyroid