我正在寻找C#和WPF的解决方案。 我尝试将多个文件上传到服务器。每次上传都应显示在进度条的列表框中。
我有一个带有进度条和文本块的WPF列表框模板:
<ListBox Name="lbUploadList" HorizontalContentAlignment="Stretch" Margin="530,201.4,14.2,33.6" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="0,2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding File}" />
<ProgressBar Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding Percent}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public class UploadProgress
{
public string File { get; set; }
public int Percent { get; set; }
}
List<UploadProgress> uploads = new List<UploadProgress>();
uploads.Add(new UploadProgress() { File = "File.exe", Percent = 13 });
uploads.Add(new UploadProgress() { File = "test2.txt", Percent = 0 });
lbUploadList.ItemsSource = uploads;
如何更新此列表中的进度条?
有人可以帮我找到正确的解决方案吗? :)
答案 0 :(得分:3)
首先,您需要在课堂上实施INotfyPropertyChanged
interface。然后你应该将进度条值绑定到ViewModel,如下所示:
public class UploadProgress : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private int percent = 0;
public int Percent
{
get { return percent; }
set
{
if (value != percent)
{
percent = value;
NotifyPropertyChanged();
}
}
}
}
我希望这会有所帮助。
答案 1 :(得分:0)
您的UploadProgress-class必须实现INotifyPropertyChanged,以便在绑定值发生变化时通知绑定。
现在您只需更改列表中某些UploadProgress实例的Percent-value即可更改相应的ProgressBars值。
也许您创建了一个设置Percentage值的方法,如:
private void Upload(UploadProgress upload)
{
byte[] uploadBytes = File.GetBytes(upload.File);
step = 100/uploadBytes.Length;
foreach (byte b in uploadBytes)
{
UploadByte(b);
upload.Percent += step; //after you implemented INotifyPropertyChanged correctly this line will automatically update it's prograssbar.
}
}
我真的不知道上传是如何工作的,所以这个方法只是为了向您展示如何处理百分比值。