How to update progress bar value in listview in WPF

Nehal Chaudhari 41 Reputation points
2022-01-23T09:46:13.247+00:00

I am developing a Download Manager. In which i am add files list in listview. in listview i have added progressbar. but how can i update its value.
Value should be updated as the file downloads.
167563-screenshot-2022-01-22-132359.png

This is my MainWindow.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using System.Windows;  
using System.Net;  
using System.ComponentModel;  
using System.Windows.Controls;  
using System.Windows.Data;  
using System.Windows.Documents;  
using System.Windows.Input;  
using System.Windows.Media;  
using System.Windows.Media.Imaging;  
using System.Windows.Navigation;  
using System.Windows.Shapes;  
  
namespace DownloadManager  
{  
    /// <summary>  
    /// Interaction logic for MainWindow.xaml  
    /// </summary>  
    public partial class MainWindow : Window  
    {  
            List<string> Namelist = new List<string>();  
        public MainWindow()  
        {  
  
            InitializeComponent();  
              
        }  
  
        private void Add_MouseUp(object sender, MouseButtonEventArgs e)  
        {  
            Add_URL au = new Add_URL();  
              
                au.ShowDialog();  
              
              
        }  
            WebClient client1 = new WebClient();  
        public void download(Add_URL a, String Text)  
        {  
            Uri uri = new Uri(Text);  
            String FileName = System.IO.Path.GetFileName(uri.AbsolutePath);  
            client1.DownloadFileAsync(uri, "E:/" + FileName);  
            client1.DownloadProgressChanged += downloadprogress;  
        }  
  
         
        private void Pause_MouseUp(object sender, MouseButtonEventArgs e)  
        {  
             
  
           // client = new WebClient();  
            client1.CancelAsync();  
           // MessageBoxResult result = MessageBox.Show("Pause");  
              
        }  
        Double a1;  
        public class MyItem  
        {  
            public String FileName { get; set; }  
            // public string Progressbar { get; set; }  
  
            MainWindow o = new MainWindow();  
            public string Size { get; set; }  
  
            public string Time { get; set; }  
  
           private double _progress;  
           public double Progress  
           {  
                  
           get { return _progress; }  
                  
             set { _progress =o.a1; NotifyPropertyChanged("Progress"); }  
           }  
  
           public event PropertyChangedEventHandler PropertyChanged;  
           private void NotifyPropertyChanged(string propertyName = "Progress")  
           {  
            if (PropertyChanged != null)  
                  PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  
            }  
  
            public double percent  
            {  
                get;  
                set;  
            }  
        }  
          
        String filename;  
        public void AddItem(Add_URL a, String Filename)  
        {  
            filename = Filename;  
            this.FilesList.Items.Add(new MyItem { FileName = "Engineering", Progress= a1, Size ="100",Time="10.30 PM" });  
              
  
  
            // NoFiles.Visibility = Visibility.Hidden;  
            // NoFileImage.Visibility = Visibility.Hidden;  
  
        }  
        public double Percentag { get; set; }  
          
        double Percentage;  
        public void downloadprogress(object sender, DownloadProgressChangedEventArgs e)  
          {  
            pb.Minimum = 0;  
            double receive = double.Parse(e.BytesReceived.ToString());  
            double Filesize = double.Parse(e.TotalBytesToReceive.ToString());  
            Percentage = receive / Filesize* 100;  
           a1= int.Parse(Math.Truncate(Percentage).ToString());   
            pb.Value= int.Parse(Math.Truncate(Percentage).ToString());  
            //pb1.Value = pb.Value;  
           // MyItem o = new MyItem();  
            //o.percent = pb.Value;  
        }  
        private void Resume_MouseUp(object sender, MouseButtonEventArgs e)  
        {  
            MessageBoxResult result = MessageBox.Show("Resume");  
              
        }  
  
        private void Delete_MouseUp(object sender, MouseButtonEventArgs e)  
        {  
            FilesList.Items.RemoveAt(FilesList.SelectedIndex);  
  
       //    NoFileImage.Visibility=System.Windows.Visibility.Hidden;  
        }  
              
  
     //  public void hide()  
        //{  
            // this.ShowActivated = false;  
       //     NoFileImage.Visibility = Visibility.Hidden;  
         //   MessageBoxResult result = MessageBox.Show("Delete");  
        //}  
  
        private void CheckBox_Checked(object sender, RoutedEventArgs e)  
        {  
         }  
  
        private void Search_MouseUp(object sender, MouseButtonEventArgs e)  
        {  
           // Search search = new Search();  
            String name2 = "En";  
            //   search.ShowDialog();  
            //  private ListView FilesList = new ListView();  
            foreach (ListViewItem item in FilesList.Items)  
            {  
                if (!item.ToString().ToLower().Contains(name2.ToLower()))  
                {  
                    FilesList.Items.Remove(item);  
                }  
            }  
        }  
  
        private void ChangePath_MouseUp(object sender, MouseButtonEventArgs e)  
        {  
            ChangePath cp = new ChangePath();  
            cp.ShowDialog();  
        }  
  
        private void Button_Click(object sender, EventArgs e)  
        {  
            String name2 = "En";  
            int i = 0;  
            foreach (Object  item in FilesList.Items)  
            {  
                i++;  
               if (!item.ToString().ToLower().Contains(name2.ToLower()))  
               {  
                    MessageBoxResult result = MessageBox.Show(name2+ " Item Found at "+i+" Line");  
                    //FilesList.Items.Remove(item);  
                }  
                else  
                {  
                    MessageBoxResult result = MessageBox.Show("No Item Found");  
                     
                }  
            }  
        }  
    }  
}  
  

and this is my XAML code

                        <GridViewColumn.CellTemplate  >  
                            <DataTemplate >  
                                <ProgressBar x:Name="progressbar" Maximum="100" Width="140"  Value="{Binding Path=Progress}" />  
                            </DataTemplate>  
                        </GridViewColumn.CellTemplate>  
                    </GridViewColumn>
Developer technologies Windows Presentation Foundation
Developer technologies XAML
Developer technologies C#
{count} votes

3 answers

Sort by: Most helpful
  1. Ken Tucker 5,861 Reputation points
    2022-01-23T12:35:40.573+00:00

    Looks like your progressbar is bound to the progress property. So setting Progress's value should update the progress bar.

         public void downloadprogress(object sender, DownloadProgressChangedEventArgs e)
           {
             pb.Minimum = 0;
             double receive = double.Parse(e.BytesReceived.ToString());
             double Filesize = double.Parse(e.TotalBytesToReceive.ToString());
             Percentage = (receive / Filesize)* 100;
            a1= int.Parse(Math.Truncate(Percentage).ToString()); 
             pb.Value= int.Parse(Math.Truncate(Percentage).ToString());
             Progress=Precentage;
         }
    

  2. Peter Fleischer (former MVP) 19,341 Reputation points
    2022-01-23T17:50:13.797+00:00

    Hi,
    you can use Progress = e.ProgressPercentage;

    Try following demo:

    XAML:

    <Window x:Class="WpfApp1.Window101"  
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
            xmlns:local="clr-namespace:WpfApp101"  
            mc:Ignorable="d"  
            Title="NehalChaudhari-1778_220123" Height="450" Width="800">  
      <Window.DataContext>  
        <local:ViewModel/>  
      </Window.DataContext>  
      <StackPanel>  
        <Button Content="Start" Command="{Binding}" Margin="5"/>  
        <ProgressBar Minimum="0"  
                     Maximum="100"   
                     Value="{Binding Path=Progress}"   
                     Height="20"    
                     Margin="5"/>  
      </StackPanel>  
    </Window>  
    

    And ViewModel:

    using System;  
    using System.ComponentModel;  
    using System.Net;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
    using System.Windows.Input;  
      
    namespace WpfApp101  
    {  
      public class ViewModel : ICommand, INotifyPropertyChanged  
      {  
        WebClient client1 = new WebClient();  
        string Text = "https://sample-videos.com/doc/Sample-doc-file-1000kb.doc";  
        public void Execute(object parameter)  
        {  
          Uri uri = new Uri(Text);  
          String FileName = System.IO.Path.GetFileName(uri.AbsolutePath);  
          client1.DownloadFileAsync(uri, @"c:/temp/" + FileName);  
          client1.DownloadProgressChanged += downloadprogress;  
        }  
      
        public double Progress { get; set; }  
        private void downloadprogress(object sender, DownloadProgressChangedEventArgs e)  
        {  
          Progress = e.ProgressPercentage;  
          OnPropertyChanged(nameof(Progress));  
        }  
      
        public event EventHandler CanExecuteChanged;  
        public bool CanExecute(object parameter) => true;  
        public event PropertyChangedEventHandler PropertyChanged;  
        private void OnPropertyChanged([CallerMemberName] string propName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));  
      }  
    }  
    

    Result:

    167582-x.gif


  3. Peter Fleischer (former MVP) 19,341 Reputation points
    2022-01-24T16:43:37.507+00:00

    Hi,
    you can use my solution inside ListView. Try following demo:

    XAML:

    <Window x:Class="WpfApp1.Window101"  
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
            xmlns:local="clr-namespace:WpfApp101"  
            mc:Ignorable="d"  
            Title="NehalChaudhari-1778_220123" Height="450" Width="800">  
      <Window.DataContext>  
        <local:ViewModel/>  
      </Window.DataContext>  
      <ListView ItemsSource="{Binding View}">  
        <ListView.View>  
          <GridView>  
            <GridView.Columns>  
              <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>  
              <GridViewColumn Header="Download">  
                <GridViewColumn.CellTemplate  >  
                  <DataTemplate >  
                    <Button Content="Start" Command="{Binding}"/>  
                  </DataTemplate>  
                </GridViewColumn.CellTemplate>  
              </GridViewColumn>  
              <GridViewColumn>  
                <GridViewColumn.CellTemplate  >  
                  <DataTemplate >  
                    <ProgressBar x:Name="progressbar" Maximum="100" Width="140" Height="20" Value="{Binding Progress}"/>  
                  </DataTemplate>  
                </GridViewColumn.CellTemplate>  
              </GridViewColumn>  
            </GridView.Columns>  
          </GridView>  
        </ListView.View>  
      </ListView>  
    </Window>  
    

    classes:

    using System;  
    using System.Collections.ObjectModel;  
    using System.ComponentModel;  
    using System.Net;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
    using System.Windows.Data;  
    using System.Windows.Input;  
    using System.Windows.Threading;  
      
    namespace WpfApp101  
    {  
      public class ViewModel  
      {  
        public ViewModel() => cvs.Source = GetData();  
      
        CollectionViewSource cvs = new CollectionViewSource();  
        public ICollectionView View { get => cvs.View; }  
      
        private ObservableCollection<Data> GetData()  
        {  
          ObservableCollection<Data> col = new ObservableCollection<Data>();  
          for (int i = 1; i < 10; i++) col.Add(new Data() { ID = i });  
          return col;  
        }  
      }  
      
      public class Data : ICommand, INotifyPropertyChanged  
      {  
        public Data() => disp = Dispatcher.CurrentDispatcher;  
      
        private Dispatcher disp;  
        public int ID { get; set; }  
        public string Text { get; set; } = "https://sample-videos.com/doc/Sample-doc-file-1000kb.doc";  
      
        WebClient client1 = new WebClient();  
        public void Execute(object parameter)  
        {  
          if (client1.IsBusy) return;  
          Progress = 0;  
          Uri uri = new Uri(Text);  
          String FileName = System.IO.Path.GetFileName(uri.AbsolutePath);  
          client1.DownloadFileAsync(uri, @"c:/temp/" + FileName);  
          client1.DownloadProgressChanged += downloadprogress;  
        }  
      
        public double Progress { get; set; }  
        private void downloadprogress(object sender, DownloadProgressChangedEventArgs e)  
        {  
          Progress = e.ProgressPercentage;  
          OnPropertyChanged(nameof(Progress));  
        }  
      
        public event EventHandler CanExecuteChanged;  
        public bool CanExecute(object parameter) => true;  
        public event PropertyChangedEventHandler PropertyChanged;  
        private void OnPropertyChanged([CallerMemberName] string propName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));  
      }  
    }  
    

    Result:

    167878-x.gif

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.