List of Exercises

ProgressBar from Another Class in WPF C#

	    
=================XAML=======================
<Window x:Class="ProgressBar_from_Another_Class.MainWindow"
    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:ProgressBar_from_Another_Class"
    mc:Ignorable="d"
    Title="MainWindow" Height="250" Width="600">
  <Grid>
    <StackPanel>
      <Button x:Name="start1" Content="Start1" Width="120" Height="30" Margin="0,10" Click="start1_Click"/>
      <ProgressBar x:Name="progressBar1" Height="30" Width="350" Margin="0,10"/>
      <Label Name="res" Margin="20"/>
    </StackPanel>
  </Grid>
</Window>
=============ProgressBarUpdater===================
using System;
using System.Windows;
using System.Windows.Controls;

public class ProgressBarUpdater
{
  private readonly ProgressBar progressBar;

  public ProgressBarUpdater(ProgressBar progressBar)
  {
    this.progressBar = progressBar ?? throw new ArgumentNullException(nameof(progressBar));
  }

  public void UpdateProgress(double value)
  {
    Application.Current.Dispatcher.Invoke(() =>
    {
      progressBar.Value = value;
    });
  }
}

===============Calculator====================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace ProgressBar_from_Another_Class
{
  class Calculator
  {
    private ProgressBarUpdater progressBarUpdater;
    public Calculator(ProgressBar progressBar)
    {
      progressBarUpdater = new ProgressBarUpdater(progressBar);
    }
    public async Task Factorial(int n)
    {
      double res = 1;
      await System.Threading.Tasks.Task.Run(() =>
      {
        for (int i = 0; i < n; i++)
        {
          progressBarUpdater.UpdateProgress(((double)(i+1)) / n);
          System.Threading.Thread.Sleep(20);
          res *= (i + 1);
        }
      });
      MainWindow.result = res;
    }
  }
}
		
	 


Download the project of Visual Studio 2022 in DropBox Download


How to Use ProgressBar from Another Class in WPF C# C#


Video Thumbnail