4

i´am looking for a solution in C# and WPF. I try to upload multiple files to a server. Every upload should be shown in the listbox within a progressbar.

I have a WPF listbox template with a progress bar and a textblock in it:

<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;

How can i update a progress bar in this list?

Can somebody help me to find the correct solution? :)

4

2 回答 2

3

首先,您需要在您的类上实现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();
            }
        }
    }
}

我希望这有帮助。

于 2013-09-13T08:01:54.563 回答
0

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

现在您只需更改列表中某些 UploadProgress-instance 的 Percent-value 即可更改相应的 ProgressBars 值。

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

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

我真的不知道上传是如何详细工作的,所以这个方法只是为了告诉你如何处理百分比值。

于 2013-09-13T07:56:59.713 回答