绑定多个下载进度

Binding Multiple Download Progress

我在 ObservableCollection 中有一个 DownloadOperation 列表,变量有 属性 Progress.TotalBytesToReceive & Progress.BytesReceived。 当我尝试将此 属性 绑定到进度条的最大值和值时,它给我绑定表达式错误 属性 未找到。我绑定其他 属性 ResultFile.Name 并成功。有什么办法可以解决这个问题吗?

更新:

我发现我需要使用 converter from progress 来获取 totalbytes 值,但现在的问题是该值没有更新,而且 observablecollection 似乎没有观察接收到的字节值。

<ListView   DataContext="{Binding Download}"
            ItemsSource="{Binding}">
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                </Style>
            </ListView.ItemContainerStyle>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="5">
                        <TextBlock Text="{Binding ResultFile.Name}"
                                   FontSize="20"
                                   Foreground="Black"/>
                        <ProgressBar Maximum="100"
                                     Value="{Binding Progress, Converter={StaticResource ByteReceivedConverter}}"/>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
 </ListView>

我将其作为视图模型,activeDownloads 包含可观察到的下载列表。

public ObservableCollection<DownloadOperation> activeDownloads = new ObservableCollection<DownloadOperation>();

并且我尝试在代码后面提取 BytesReceived 和 TotalBytesToReceive

        double received = 0;
        double total = 0;
        foreach (var item in activeDownloads)
        {
            received += item.Progress.BytesReceived;
            total += item.Progress.TotalBytesToReceive;

        }
        if (total != 0) { 
        var percentage = received / total * 100;

它工作没有任何问题,observablecollection 也工作正常,当我添加下载时它会自动更改视图而无需我手动更新数据上下文,如果下载 finish/removed 结果相同。但是,如果我直接将 Progress.BytesReceived 绑定到进度条值,它会给我路径错误,但我能够将它绑定到 Progress 属性。所以我做了一个转换器来检索值。

这是我用来转换 Progress 的 Convereter 属性 :

public class ByteReceivedConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,      string language)
    {
        BackgroundDownloadProgress bytes = (BackgroundDownloadProgress)value;
        if (bytes.TotalBytesToReceive != 0)
            return bytes.BytesReceived/bytes.TotalBytesToReceive*100;

        else return 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

是否有可能使这个 DownloadOperation 具有字节接收级别的可观察性?因为我没有做到这一点 属性,我只是从元数据中检索它。还是我做错了?因为现在我遇到的问题是视图不知道 bytesreceived 值正在更改。

如果不可能,我是否应该制作另一个实现了 INotifyPropertyChanged 的​​视图模型?

首先,你不需要使用转换器;绑定 Max 和 Value 属性本来没问题,但您可能没有将源值设置为 public 属性,或者您在绑定中设置的路径不正确。

按照您现在的做法,每次更新 BytesReceived 时,您都需要为 Progress 属性 引发 INotifyPropertyChanged 的​​ 属性 changed 事件,因为那是 属性 你要绑定到。