猿问

如何使用 DownloadFileAsync 进度百分比更新 listView 中的文本?

我目前正在制作一个播客客户端来下载剧集。我有一个 listView 填充了一个提要的剧集,然后当你双击一个时,它会将它放入一个单独的“下载”lisview,它有一个“名称”和一个“进度”列。


我遇到的问题是尝试在异步下载时单独更新每个进度。因为我不确定如何跟踪每个 ListViewItem 的进度以及如何在 downloadProgressChanged 函数中引用它。


        private void lvPodDownloads_SelectionChanged(object sender, SelectionChangedEventArgs e)

    {

        if (lvPodEpisodes.SelectedItems.Count == 1) // Check if an item is selected just to be safe

        {

            ListViewItem item = (ListViewItem)lvPodEpisodes.SelectedItem;

            string[] epInfo = (string[])item.Tag;

            txtTitle.Text = epInfo[0];

            txtDesc.Text = epInfo[1];


            try

            {

                imgFeedImage.Source = new BitmapImage(new Uri((Environment.CurrentDirectory + "\\..\\..\\feedImages\\" + epInfo[3])));

            }

            catch (Exception) // If it fails to set the image (Eg. It's non-existent) It will leave it blank

            {

                imgFeedImage.Source = null;

            }

        }

    }

    private void lvPodEpisodes_MouseDoubleClick(object sender, MouseButtonEventArgs e) // Downloading the episode in here

    {

        if (e.ChangedButton == MouseButton.Left) // Left button was double clicked

        {

            ListViewItem selected = (ListViewItem)lvPodEpisodes.SelectedItem;

            string[] epInfo = (string[])selected.Tag;


            Uri downloadUrl = new Uri(epInfo[2]);




            List<Episode> downloading = new List<Episode>();

            downloading.Add(new Episode() { Title = epInfo[0], Progress = "0%" });

            lvPodDownloads.Items.Add((new Episode() { Title = epInfo[0], Progress = "0%" }));

            using (WebClient client = new WebClient())

            {

                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

            }

        }

    }


这是程序下载部分的代码示例。


这是我到目前为止所拥有的图像:https : //s33.postimg.cc/gthzioxlr/image.png


月关宝盒
浏览 169回答 1
1回答

手掌心

您应该向 ProgressChanged 方法添加一个额外的参数。private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Episode curEpisode){&nbsp; &nbsp; curEpisode.Progress = $"{e.ProgressPercentage} %";}并像这样修改处理程序设置:List<Episode> downloading = new List<Episode>();var newEpisode = new Episode() { Title = epInfo[0], Progress = "0%" };&nbsp;&nbsp;downloading.Add(newEpisode);lvPodDownloads.Items.Add(newEpisode);using (WebClient client = new WebClient()){&nbsp; &nbsp; client.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, newEpisode));}静态属性intDownloadProgress就没有用了。您还应该考虑将可观察集合用于剧集列表,并通过 XAML 代码将其用于绑定。
随时随地看视频慕课网APP
我要回答