WPF(Windows Presentation Foundation)是微软推出的基于Windows的用户界面框架,它提供了丰富的图形和动画功能,非常适合构建现代化的桌面应用程序。在WPF中下载多个文件并在弹出窗口中显示进度,涉及到多线程处理、异步编程以及UI更新等概念。
以下是一个简单的WPF应用程序示例,展示了如何下载多个文件并在弹出窗口中显示进度:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace WpfApp
{
public partial class MainWindow : Window
{
private List<string> downloadUrls = new List<string>
{
"http://example.com/file1.zip",
"http://example.com/file2.zip",
"http://example.com/file3.zip"
};
public MainWindow()
{
InitializeComponent();
}
private async void StartDownloadButton_Click(object sender, RoutedEventArgs e)
{
var progressWindow = new ProgressWindow();
progressWindow.Show();
await DownloadFilesAsync(progressWindow);
}
private async Task DownloadFilesAsync(ProgressWindow progressWindow)
{
for (int i = 0; i < downloadUrls.Count; i++)
{
var url = downloadUrls[i];
var fileName = Path.GetFileName(new Uri(url).AbsolutePath);
progressWindow.UpdateProgress($"Downloading {fileName}...", (i + 1) * 100 / downloadUrls.Count);
await DownloadFileAsync(url, fileName);
}
progressWindow.Close();
}
private async Task DownloadFileAsync(string url, string fileName)
{
using (var client = new HttpClient())
{
var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
using (var stream = await response.Content.ReadAsStreamAsync())
using (var fileStream = new FileStream(fileName, FileMode.Create))
{
await stream.CopyToAsync(fileStream);
}
}
}
}
public partial class ProgressWindow : Window
{
public ProgressWindow()
{
InitializeComponent();
}
public void UpdateProgress(string message, int percentage)
{
Dispatcher.Invoke(() =>
{
ProgressLabel.Content = message;
ProgressBar.Value = percentage;
});
}
}
}
Dispatcher.Invoke
或Dispatcher.BeginInvoke
来确保在正确的线程上执行UI更新。通过上述方法和注意事项,可以在WPF应用程序中实现稳健的多文件下载功能,并提供良好的用户反馈。
没有搜到相关的文章