参考下面的屏幕截图,我有以下视图和视图模型设置来表示进度条下载。当我向这个下载集合添加超过 1 个下载时,下载 1 似乎会覆盖下载 2 的 Progress() 公共属性。
下面的示例是下载 1 正在下载 1MB,它将首先完成,与下载 2 下载 5MB 相比。下载 1 完成后,下载 2(下面的 hello2 示例)进度条就停在那里,但字节仍在后台下载,直到达到 5MB。
如何更改代码以确保下载 1 不会干扰下载 2 的进度条 UI。我尝试将 Progress() 修改为私有,但两个进度条 UI 均未显示
看法
<ItemsControl Name="MyItemsControl" ItemsSource="{Binding GameDownloads}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid DockPanel.Dock="Right">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding GameName}" />
<ProgressBar Grid.Row="0" Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding Progress, Mode=OneWay}" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding StatusText}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
下载AppViewModel
Public Class DownloadAppViewModel
Inherits ViewModelBase
Private ReadOnly WC As WebClient
Public Sub New(ByVal Name As String, ByVal URL As String, ByVal FileName As String)
_gameName = Name
WC = New WebClient
AddHandler WC.DownloadFileCompleted, AddressOf DownloadCompleted
AddHandler WC.DownloadProgressChanged, AddressOf DownloadProgressChanged
WC.DownloadFileAsync(New Uri(URL), FileName)
End Sub
Private Sub DownloadCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
End Sub
Private Sub DownloadProgressChanged(ByVal sender As [Object], ByVal e As DownloadProgressChangedEventArgs)
If _totalSize = 0 Then
_totalSize = e.TotalBytesToReceive
End If
DownloadedSize = e.BytesReceived
End Sub
Private _gameName As String
Public Property GameName() As String
Get
Return _gameName
End Get
Set(ByVal value As String)
_gameName = value
Me.OnPropertyChanged("GameName")
End Set
End Property
Public ReadOnly Property StatusText() As String
Get
If _downloadedSize < _totalSize Then
Return String.Format("Downloading {0} MB of {1} MB", _downloadedSize, _totalSize)
End If
Return "Download completed"
End Get
End Property
Private _totalSize As Long
Private Property TotalSize() As Long
Get
Return _totalSize
End Get
Set(ByVal value As Long)
_totalSize = value
OnPropertyChanged("TotalSize")
OnPropertyChanged("Progress")
OnPropertyChanged("StatusText")
End Set
End Property
Private _downloadedSize As Long
Private Property DownloadedSize() As Long
Get
Return _downloadedSize
End Get
Set(ByVal value As Long)
_downloadedSize = value
OnPropertyChanged("DownloadedSize")
OnPropertyChanged("Progress")
OnPropertyChanged("StatusText")
End Set
End Property
Public ReadOnly Property Progress() As Double
Get
If _totalSize <> 0 Then
Return 100.0 * _downloadedSize / _totalSize
Else
Return 0.0
End If
End Get
End Property
End Class