List of Exercises

How to use ProgressBar in C# WPF

	    
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
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 WPF_ProgressBar
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
    private readonly ViewModel _viewModel = new ViewModel();
    public MainWindow()
    {
      DataContext = _viewModel;
      InitializeComponent();
    }

    private void start1_Click(object sender, RoutedEventArgs e)
    {
      SynchronizationContext context = SynchronizationContext.Current;
      Thread backgroundThread = new Thread(
          new ThreadStart(() =>
          {
            for (int n = 0; n < 100; n++)
            {
              Thread.Sleep(50);
              context?.Post(new SendOrPostCallback((o) =>
              {
                progressBar1.Value = n;
              }), null);
            };
          }
        ));
      backgroundThread.Start();
    }

    private void start2_Click(object sender, RoutedEventArgs e)
    {
      Task.Run(() =>
      {
        for (int n = 0; n <= 100; n++)
        {
          // simulates some costly computation
          Thread.Sleep(50);

          // periodically, update the progress
          _viewModel.ProgressValue = n;
        }
      });
    }

    private async void start3_Click(object sender, RoutedEventArgs e)
    {
      int totalSteps = 100;
      for (int i = 0; i <= totalSteps; i++)
      {
        // Update progress bar
        progressBar3.Value = i * (100.0 / totalSteps);

        // Simulate a task delay
        await Task.Delay(50);
      }
    }
  }

  class ViewModel : INotifyPropertyChanged
  {
    private double _progressValue;

    public double ProgressValue
    {
      get { return _progressValue; }
      set { _UpdatePropertyField(ref _progressValue, value); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void _UpdatePropertyField<T>(
      ref T field, T value, [CallerMemberName] string propertyName = null)
    {
      if (!EqualityComparer<T>.Default.Equals(field, value))
      {
        field = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
    }
  }
}
		
	 


Download the project of Visual Studio 2022 in DropBox Download


How to Use ProgressBar in WPF C# - 3 Examples - WPF C# Examples for ProgressBar


Video Thumbnail