使用 wpf 进度条上传多个文件

本文关键字:文件 wpf 使用 | 更新日期: 2023-09-27 18:31:13

我正在寻找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;

如何更新此列表中的进度条?

有人可以帮助我找到正确的解决方案吗?:)

使用 wpf 进度条上传多个文件

首先,

您需要在类上实现INotfyPropertyChanged接口。然后,您应该能够将进度条值绑定到 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();
            }
        }
    }
}

我希望这有所帮助。

UploadProgress-class 必须实现 INotifyPropertyChanged,以便在绑定的值更改时通知绑定。

现在,您只需更改列表中某些UploadProgress实例的百分比值即可更改相应的进度条值。

也许您创建了一个设置百分比值的方法,例如:

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.
    }
}

我真的不知道上传是如何详细工作的,所以这种方法只是为了向您展示如何处理百分比值。