UWP 在 ListView 中更新多个 ProgressBars

UWP Update multiple ProgressBars inside ListView

在我的 UWP 应用程序中,我有一个带有已定义 ItemTemplate 的 ListView。在这个模板中,有一个 ProgressBar。现在,如果我启动多个 BackgroundTransfers(下载),我将获得所有活动的下载并将它们添加到 ObservableCollection<MyClass> 并将此集合设置为我的 ListView 中的 ItemsSource。现在我的问题是,如何更新这些 ProgressBars?我已经阅读了一些有关 INotifyPropertyChanged 的​​内容,但这是唯一正确的方法吗?

此致

Now my question is, how can i update these ProgressBars? I have read something about the INotifyPropertyChanged, but is this the right and only way to go?

INotifyPropertyChanged 接口用于通知客户端(通常是绑定客户端)属性 值已更改。我正在使用它来更新 BackgroundTransfers 的 ProgressBars。

主要步骤如下:

首先,为MyClass实现INotifyPropertyChanged接口:

public class MyClass : INotifyPropertyChanged
{
    public DownloadOperation DownloadOperation { get; set; }

    private int _progress;
    public int Progress
    {
        get
        {
            return _progress;
        }
        set
        {
            _progress = value;
            RaisePropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged([CallerMemberName] string name = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

其次,将ProgressBar的值绑定到XAML中的Progress属性:

<ProgressBar Value="{Binding Progress}" Margin="0,5"></ProgressBar>

然后,使用Progress调用回调来更新后面代码中的进度:

Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
await download.AttachAsync().AsTask(cancelToken.Token, progressCallback);


private void DownloadProgress(DownloadOperation download)
    {
        try
        {
            MyClass myClass = myClasses.First(p => p.DownloadOperation == download);
            myClass.Progress = (int)((download.Progress.BytesReceived * 100) / download.Progress.TotalBytesToReceive);
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.ToString());
        }
    }

这里是完整的BackgroundTransferDemo供您参考。