I'm new at programming in WPF and C# and getting used to OOP, I'm trying to code my program using the best programming practices but I have been stuck for a couple of days now and I wasn't able to figure out how to complete this, hope someone out there can help.
what I'm trying to do is very simple, I have a WPF window with a progress bar and a button, that's it, and in the C# backend code for this window, I have a click event that calls a method in another class from another file, in that class I have a BackgroundWorker and I have been trying to update a ProgressBar based on the BackgroundWorker.
I confirmed that the code works by writing the progress and events in the console, what I have not idea how to do is how to access that BackgroundWorker in the other class to update the progress bar in my xaml file, or if this is not the best approach I would like to know what would be the best way to do this
XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="35"/>
<RowDefinition Height="15"/>
<RowDefinition Height="40"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<ProgressBar x:Name="progressBar"
Grid.Row = "1"
Width ="500"
Value="0"/>
<Button x:Name="btn_start"
Grid.Row = "3"
Content ="Start"
Height="30"
Width="125"
Click="btn_start_Click"/>
</Grid>
c# XAML Backend:
namespace progressBar
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btn_start_Click(object sender, RoutedEventArgs e)
{
GeneralTasks GT = new GeneralTasks();
GT.start();
}
}
}
And finally the unreadable class "GeneralTasks":
public class GeneralTasks
{
BackgroundWorker worker = new BackgroundWorker();
public void start()
{
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerAsync();
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine(e.ProgressPercentage + "% " + (string)e.UserState);
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
worker.ReportProgress(0, string.Format("Percentage completed: 0"));
for (int i = 0; i <= 100; i++)
{
worker.ReportProgress(i, string.Format("Percentage completed: {0}", i));
Console.WriteLine("Percentage Completed: {0}",i);
Thread.Sleep(100);
}
worker.ReportProgress(100, string.Format("Done Processing"));
}
private void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Done Processing");
}
}