Reputation: 233
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? :)
Upvotes: 4
Views: 3655
Reputation: 6014
Your UploadProgress-class has to implement INotifyPropertyChanged, to notify the binding when it's value changes.
Now you just have to change the Percent-value of some UploadProgress-instance in your list to change the corresponding ProgressBars value.
Maybe you create a method which sets the Percentage value, like:
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.
}
}
I really don't know how a upload works in detail, so this method is just to show you how you could handle the percentage value.
Upvotes: 0
Reputation: 23831
Firstly you will need to implement INotfyPropertyChanged
interface on your class. Then you should be in a position to bind the progress bar value to the ViewModel like so:
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();
}
}
}
}
I hope this helps.
Upvotes: 3