为ProgressBar
做动画时遇到问题。
我的目标是,每次处理ProgressBar.Value
和CopyAsync
时,我都希望CreateFolderAsync
更新。
我的xaml文件中有4个组件,每次完成该过程(CopyAsync
和CreateFolderAsync
)时都会更新,TextBlock
运行正常,每次都会更新过程完成。问题在于ProgressBar
它将在所有过程结束时更新UI。
我正在使用Dispatcher.RunAsync
,以及我放入TextBlock
和ProgressBar
的更新过程。
请告知,如何更新以下代码的ProgressBar
。
MainPage.xaml中
<TextBlock Text="Files:" FontSize="72" Margin="363,270,834,402"></TextBlock>
<TextBlock Text="Folders:" FontSize="72" Margin="273,411,834,270"></TextBlock>
<TextBlock x:Name="Files" FontSize="72" Margin="582,270,609,402"></TextBlock>
<TextBlock x:Name="Folders" FontSize="72" Margin="582,411,588,270"></TextBlock>
<ProgressBar x:Name="FolderBar" Height="25" Margin="10,532,-10,211"></ProgressBar>
<ProgressBar x:Name="FileBar" Height="25" Margin="10,565,-10,178"></ProgressBar>
MainPage.xaml.cs中
private async void CopyFolder(string path)
{
IStorageFolder destination = ApplicationData.Current.LocalFolder;
IStorageFolder root = Package.Current.InstalledLocation;
if (path.Equals(ROOT) && !await FolderExistAsync(ROOT))
await destination.CreateFolderAsync(ROOT);
destination = await destination.GetFolderAsync(path);
root = await root.GetFolderAsync(path);
IReadOnlyList<IStorageItem> items = await root.GetItemsAsync();
// For count the total files
if (path.Equals(ROOT))
TotalFiles(path);
foreach (IStorageItem item in items)
{
if (item.GetType() == typeof(StorageFile))
{
IStorageFile presFile = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///" + path.Replace("\\", "/") + "/" + item.Name));
if (!await FileExistAsync(path, item.Name))
{
IStorageFile copyFile = await presFile.CopyAsync(destination);
countFiles++;
if (copyFile != null)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
// The update for TextBlock is fine
Files.Text = countFiles.ToString();
// But for the ProgressBar it will update in the end of process
FileBar.Value = countFiles / totalFiles * 100;
});
}
}
}
else
{
if (!await FolderExistAsync(path + "\\" + item.Name))
{
StorageFolder createFolder = await destination.CreateFolderAsync(item.Name);
countFolders++;
if (createFolder != null)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
// The update for TextBlock is fine
Folders.Text = countFolders.ToString();
// But for the ProgressBar it will update in the end of process
FolderBar.Value = countFolders / totalFolders * 100;
});
}
}
CopyFolder(path + "\\" + item.Name);
}
}
}
答案 0 :(得分:1)
countFiles
和totalFiles
都是整数,所以当你将一个除以另一个时,它会执行整数除法;由于totalFiles
始终大于或等于countFiles
,因此结果始终为0,除非它在1的末尾。
要解决此问题,您需要在划分之前强制转换为double
,以便执行浮点除法:
FileBar.Value = (double)countFiles / totalFiles * 100;