How to use Dispatcher for updating a progressbar in WPF [duplicate] - c#

I have a WPF application which is built on the MVVM design pattern.
I wish to implement a progress bar in the app, that follows the MVVM pattern.
Does any one have any suggestions on how to implement this?
Thanks in advance

Typically your UI would simply bind to properties in your VM:
<ProgressBar Value="{Binding CurrentProgress, Mode=OneWay}"
Visibility="{Binding ProgressVisibility}"/>
Your VM would use a BackgroundWorker to do the work on a background thread, and to periodically update the CurrentProgress value. Something like this:
public class MyViewModel : ViewModel
{
private readonly BackgroundWorker worker;
private readonly ICommand instigateWorkCommand;
private int currentProgress;
public MyViewModel()
{
this.instigateWorkCommand =
new DelegateCommand(o => this.worker.RunWorkerAsync(),
o => !this.worker.IsBusy);
this.worker = new BackgroundWorker();
this.worker.DoWork += this.DoWork;
this.worker.ProgressChanged += this.ProgressChanged;
}
// your UI binds to this command in order to kick off the work
public ICommand InstigateWorkCommand
{
get { return this.instigateWorkCommand; }
}
public int CurrentProgress
{
get { return this.currentProgress; }
private set
{
if (this.currentProgress != value)
{
this.currentProgress = value;
this.OnPropertyChanged(() => this.CurrentProgress);
}
}
}
private void DoWork(object sender, DoWorkEventArgs e)
{
// do time-consuming work here, calling ReportProgress as and when you can
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.CurrentProgress = e.ProgressPercentage;
}
}

Use a ProgressBar control and bind its Value property to a property of the ViewModel:
View
<ProgressBar Minimum="0" Maximum="0" Value="{Binding CurrentProgress}" />
ViewModel
private double _currentProgress;
public double CurrentProgress
{
get { return _currentProgress; }
private set
{
_currentProgress = value;
OnPropertyChanged("CurrentProgress");
}
}

Add two properties to your VM:
bool IsProgressBarVisible
double ProgressValue
If you start a long time operation in your VM, set the IsProgressBarVisible-property to true and set the ProgressValue periodical to the current progress value. Try to calculate a value between 0 and 100. This has the advantage that you don't have to provide a minimum and maximum value.
After the asynchronous operation has completed, set the IsProgressBarVisible to false.
In XAML, bind to these two properties. Use a value converter to convert the boolean visibility to a Visibility.
<ProgressBar Value="{Binding ProgressValue}" Visibility="{Binding IsProgressBarVisible,Converter={StaticResource BooleanToVisibility_ValueConverter}}"/>

Related

Using progress bar in WPF C# MVVM

My goal is to update the progress bar while another set of script (calculations) is running.
I have followed the sample files from here and tried to bind it to my MVVM script but the progress bar would not update.
Here is the Progressbar script
In the script below, I have included progressBarCounter and noOfDataas a value in another script that is calculated in a method.
Proof that data is updated
public partial class ProgressBarTaskOnWorkerThread : Window
{
public ProgressBarTaskOnWorkerThread()
{
InitializeComponent();
}
private void Window_ContentRendered(object sender, EventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
EtabsDataFormatting.ViewModel.SpliceViewModel data = new EtabsDataFormatting.ViewModel.SpliceViewModel();
for (int i = data.progressBarCounter; i < data.noOfData;)
{
(sender as BackgroundWorker).ReportProgress(i);
}
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbStatus.Value = e.ProgressPercentage;
int perc = Convert.ToInt32(pbStatus.Value);
UpdateProgress(perc);
}
public void UpdateProgress(int percentage)
{
pbStatus.Value = percentage;
if (percentage == 100)
{
Close();
}
}
}
Here is part of my XAML code for the button to start calculations and run the progressbar
The command Binding = RunCalcBtn is bound to the calculation scripts, therefore, I have created a click to run the progress bar instead.
<Button x:Name = "ApplyButton" Margin="0 1 0 1" Content ="Start Calculation" Command="{Binding RunCalcBtn, Mode=TwoWay}" Click ="PrgBar_Click"/>
Progressbar XAML.cs button click
This part displays the progress bar, but it does not update.
private void PrgBar_Click(object sender, RoutedEventArgs e)
{
ProgressBar.ProgressBarTaskOnWorkerThread progressWindow = new ProgressBar.ProgressBarTaskOnWorkerThread();
progressWindow.Show();
}
Thank you so much for helping me in advance!
As Flithor has said, the best way to achieve this is with Progress<T>.
I give a short illustration of how to use this.
Firstly you need to create a Property in your View Model so that you can bind the ProgressBar's Value to something. Your ViewModel will need to implement INotifyPropertyChanged so that the Property set can invoke RaisePropertyChangedEvent.
Next create a Progress inside the method called by the Button click and pass it to your worker method. Use an ICommand for this, so that it can be bound to your Button (you don't need the Click event). Something like this:
var progress = new Progress<int>(percent =>
{
ProgressProperty = percent;
});
await Task.Run(() => myWorker(progress));
Finally within your worker method you periodically update the value like this:
private void myWorker(IProgress<int> progress)
{
progress.Report(1);
// ...
progress.Report(100);
}
By way of explanation: I used an integer, but you can also use a double if you want really fine calculations! The constructor of the Progress object takes the ProgressProperty (the name I gave to the property that gets bound to the ProgressBar) as a parameter. This means that when the worker calls Report(), the ProgressProperty is automatically updated with the new value, and hence can be reflected in the UI. Finally your worker method is invoked with await so that the UI is able to update on every incremented value.
For a very full explanation on Progress, see Stephen Cleary's blog
In MVVM WPF, you should do this to take full advantage of it:
View:
<Grid>
<ProgressBar Name="myProgressBar"
Minimum="0"
Value="{Binding ProgressBarValue,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
Maximum="100"
Foreground="{Binding ColorState,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
Background="#424242"
BorderBrush="Transparent"
BorderThickness="0"/>
<TextBlock Text="{Binding ElementName=myProgressBar, Path=Value,Mode=OneWay,UpdateSourceTrigger=PropertyChanged, StringFormat={}{0:0}%}"
FontWeight="DemiBold"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
ViewModel:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Threading;
namespace YourNameSpace.Models
{
public class Device : INotifyPropertyChanged
{
public Device()
{
this.ProgressBarValue = 50; // Your ProgressBar Foreground will be "GREEN" automatically
// This is the
}
private double progressBarValue;
public double ProgressBarValue
{
get { return progressBarValue; }
set
{
progressBarValue = value;
if(progressBarValue < 50)
this.ColorState = "Red";
else if (progressBarValue >= 50)
this.ColorState = "Green";
NotifyPropertyChanged("ProgressBarValue");
}
}
private string colorState = "Transparent";
public string ColorState
{
get { return colorState; }
set { colorState = value; NotifyPropertyChanged("ColorState"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string Obj)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(Obj));
}
}
}
}
You can REMOVE this from your code:
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbStatus.Value = e.ProgressPercentage;
int perc = Convert.ToInt32(pbStatus.Value);
UpdateProgress(perc);
}
public void UpdateProgress(int percentage)
{
pbStatus.Value = percentage;
if (percentage == 100)
{
Close();
}
}
And ONLY use this:
for (int i = data.progressBarCounter; i < 100; i++)
{
ProgressBarValue = i;
}
Your
ProgressBar Value
Progress Foreground Color
will be updated automatically.

Using a Stopwatch and DataBinding on a WPF Window that is already being updated using IProgress

In my Main() WPF program I run a time consuming method asynchronously. When this method is running, I fire up a secondary window that contains a ProgressBar, which I update using IProgress.
Following is an example of my setup.
MAIN Program:
public partial class MainWindow : Window
{
private ProgressBarWindow pbwWindow = null;
public MainWindow()
{
InitializeComponent();
}
private void RunMethodAsync(IProgress<int> progress)
{
Dispatcher.Invoke(() =>
{
pbwWindow = new ProgressBarWindow("Processing...");
pbwWindow.Owner = this;
pbwWindow.Show();
});
TimeConsumingMethod(progress);
}
private void TimeConsumingMethod(IProgress<int> progress)
{
for (int i = 1; i <= 100; i++)
{
// Thread.Sleep() represents actual time consuming work being done.
Thread.Sleep(100);
progress.Report(i);
}
}
private async void btnRun_Click(object sender, RoutedEventArgs e)
{
IProgress<int> progress;
progress = new Progress<int>(i => pbwWindow.SetProgressUpdate(i));
await Task.Run(() => RunMethodAsync(progress));
}
}
My ProgressBarWindow which contains the progress bar looks like this:
public partial class ProgressBarWindow : Window
{
Stopwatch stopwatch = new Stopwatch();
BackgroundWorker worker = new BackgroundWorker();
public string ElapsedTimeString { get; set; }
public ProgressBarWindow(string infoText)
{
InitializeComponent();
SetTimer();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
StartTimer();
}
private void SetTimer()
{
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += (s, e) =>
{
while (!worker.CancellationPending)
{
worker.ReportProgress(0, stopwatch.Elapsed);
Thread.Sleep(1000);
}
};
worker.ProgressChanged += (s, e) =>
{
TimeSpan elapsedTime = (TimeSpan)e.UserState;
ElapsedTimeString = string.Format("{0}:{1}:{2}", elapsedTime.Minutes, elapsedTime.Seconds, elapsedTime.Milliseconds);
};
}
private void StartTimer()
{
stopwatch.Start();
worker.RunWorkerAsync();
}
private void StopTimer()
{
stopwatch.Stop();
worker.CancelAsync();
}
public void SetProgressUpdate(int progress)
{
pbLoad.Value = progress;
if (progress >= 100)
{
StopTimer();
Close();
}
}
}
I borrowed the StopWatch logic from this SO answer.
Then, on my ProgressBarWindow I have a TextBlock which I've used Binding as follows, just as the answer above says.
<TextBlock Name="tbElapsedTime" Text="{Binding ElapsedTimeString}"/>
Now when I run the program, the method executes, and the progress bar updates just fine. However, my TextBlock that's supposed to update with the elapsed time does not get updated.
To verify my timer's running fine, I updated TextBlock value directly as follows instead of Binding and it worked as expected and displayed Elapsed Time:
worker.ProgressChanged += (s, e) =>
{
TimeSpan elapsedTime = (TimeSpan)e.UserState;
ElapsedTimeString = string.Format("{0}:{1}:{2}", elapsedTime.Minutes, elapsedTime.Seconds, elapsedTime.Milliseconds);
tbElapsedTime.Text = ElapsedTimeString;
};
So I'm guessing my problem is with the Binding and possibly using BackgroundWorker on a windows that's already being run asynchronously? How could I fix this so I could use DataBinding?
As mentioned by Ginger Ninja, you have to implement INotifyPropertyChanged and use RelativeSource={RelativeSource Self} (as additional setting to the binding):
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _ElapsedTimeString;
public string ElapsedTimeString
{
get { return _ElapsedTimeString; }
set
{
if (_ElapsedTimeString != value)
{
_ElapsedTimeString = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ElapsedTimeString"));
}
}
}
// ....
}
and the XAML:
<TextBlock Name="tbElapsedTime" Text="{Binding ElapsedTimeString, RelativeSource={RelativeSource Self}}"/>
Data binding is often used in combination with MVVM. That is IMHO the prefered way to solve your problem... If you want to use MVVM, you have to implement a view model that contains all the logic and implements INotifyPropertyChanged. Than you can simply bind properties from the view model to the view. That ensures a nice separation between (GUI related) logic and view.

WPF percentage status shown in label MVVM

I got some problem in showing download percentage in GridView of WCF. I used MVVM pattern.
Here is my background worker in application start:
public partial class MainWindow : Window
{
public MainWindow()
{
Overall.EverythingOk = "Nothing";
InitializeComponent();
//IRepo repo = new Repo();
ViewModel.MainWindowsViewModel viewModel = new ViewModel.MainWindowsViewModel();
this.DataContext = viewModel;
BackGroundThread bgT = new BackGroundThread();
bgT.bgWrk.RunWorkerAsync();
}}
Here is the DoWork function in BackGroundTHread class
public void bw_DoWork(object sender, DoWorkEventArgs e)
{
if (!Overall.stopStatus)
{
for (int i=0; i < 10000; i++)
{
Overall.PercentageDwnd = i;
Overall.caseRefId = "999999";
if (i == 9998)
{
i = 1;
}
}
}
}
Overall.PercentageDwnd and Overall.caseRefId are static variable (you can call from everywhere in the application) and always update until the background worker completed. I got another ViewModel called TestViewModel and here it is.
public class TestViewModel:BindableBase
{
private String _UpdatePer=Overall.PercentageDwnd.ToString();
public String UpdatePercentage
{
get { return _UpdatePer; }
set { SetProperty(ref _UpdatePer, value); }
}
private ObservableCollection _ViewAKA = new ObservableCollection();
private tblTransaction model;
public TestViewModel(tblTransaction model)
{
// TODO: Complete member initialization
}
public ObservableCollection ViewAKA
{
get { return _ViewAKA; }
set { SetProperty(ref _ViewAKA, value); }
}
}
I bind with TestView.xaml file
<Window x:Class="EmployeeManager.View.TestView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestView" Height="359.774" Width="542.481">
<Grid Margin="0,0,2,0">
<Label Content="{Binding UpdatePercentage,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Background="Red" Foreground="White" Margin="130,86,0,0" VerticalAlignment="Top" Width="132" Height="39">
</Label>
</Grid>
</Window>
There is no real time update at Label even though I bind UpdatePercentage to it. How can I update real time to label?
The problem is that you are updating the static properties, which are not bound to anything. You need to update and raise the property changed notification for the properties which are bound to the label controls, i.e. UpdatePercentage
Can you pass the TestViewModel instance into the RunWorkerAsync call?
bgT.bgWrk.RunWorkerAsync(testViewModel);
And then access in the DoWork event handler:
public void bw_DoWork(object sender, DoWorkEventArgs e)
{
if (!Overall.stopStatus)
{
var viewModel = e.Argument as TestViewModel;
for (int i=0; i < 10000; i++)
{
Overall.PercentageDwnd = i;
viewModel.UpdatePercentage = i;
Overall.caseRefId = "999999";
if (i == 9998)
{
i = 1;
}
}
}
}
Here is answer link:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/02a7b9d1-1c26-4aee-a137-5455fee175b9/wpf-percentage-status-shown-in-label-mvvm?forum=wpf
i need to trigger when the Overall.PercentageDwnd property changes.
Edited
In Overall Class:
public class Overall
{
private static int _percentage;
public static int PercentageDwnd
{
get { return _percentage; }
set
{
_percentage = value;
//raise event:
if (PercentageDwndChanged != null)
PercentageDwndChanged(null, EventArgs.Empty);
}
}
public static string caseRefId { get; set; }
public static bool stopStatus { get; set; }
public static event EventHandler PercentageDwndChanged;
}
In TestViewModel:
public class TestViewModel : BindableBase
{
private String _UpdatePer = Overall.PercentageDwnd.ToString();
public String UpdatePercentage
{
get { return _UpdatePer; }
set { SetProperty(ref _UpdatePer, value); }
}
public TestViewModel(tblTransaction model)
{
Overall.PercentageDwndChanged += Overall_PercentageDwndChanged;
// TODO: Complete member initialization
}
private void Overall_PercentageDwndChanged(object sender, EventArgs e)
{
this.UpdatePercentage = Overall.PercentageDwnd.ToString();
}
}
Since you have bound the TextBlock in the view to the UpdatePercentage source property, you need to set this one and raise the PropertyChanged event whenever you want to update the Label in the view. This means that you need to know when the Overall.PercentageDwnd property changes.
Credit to
Magnus (MM8)
(MCC, Partner, MVP)
Thanks All

Updating Bitmap from BackgroundWorker in MVVM/WPF

I'm trying to update a BitmapImage in the UI from a BackgroundWorker thread. I know enough about background workers to generally set them up, and how to use an ObservableCollection to update a list from a BackgroundWorker, but I'm struggling getting the image to update.
When I set
So far it looks like this:
XAML:
<Image Source="{Binding ImageSource}" />
ViewModel:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private BitmapImage ImageSource_;
public BitmapImage ImageSource
{
get { return ImageSource_; }
set { ImageSource_= value; NotifyPropertyChanged("ImageSource"); }
}
private BackgroundWorker UpdateImageBGW = new BackgroundWorker();
public ViewModel()
{
// this works fine
ImageSource = UpdateImage();
UpdateImageBGW.DoWork += new DoWorkEventHandler(UpdateImage_DoWork);
UpdateImageBGW.RunWorkerAsync();
}
private void UpdateImage_DoWork(object sender, DoWorkEventArgs e)
{
// this gets called fine and grabs the updated image, but setting it to
// ImageSource never updates the UI
ImageSource = UpdateImage();
}
}
The problem is you are trying to update a UI element from a background thread. You cannot interact with elements created on the UI thread from any other thread because of security reasons. If you want to update the UI from a background thread, do something like this:
Dispatcher.Invoke((Action)delegate() { /*update UI thread here*/ });
This method will create the bridge that allows you to talk to the UI thread. Check out this stackoverflow thread that has more example.
Best of Luck
use ObservableCollection like this:
public partial class MainWindow : Window
{
private ObservableCollection<int> myVar;
public ObservableCollection<int> MyProperty
{
get { return myVar; }
set { myVar = value; }
}
BackgroundWorker bw;
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
MyProperty = new ObservableCollection<int>();
bw = new BackgroundWorker();
bw.DoWork += bw_DoWork;
bw.RunWorkerAsync();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
for(int i = 0; i < 10;i++)
{
MyProperty.Add(i);
}
}
}
and xaml:
<ListBox HorizontalAlignment="Left" ItemsSource="{Binding MyProperty}" Height="224" Margin="93,50,0,0" VerticalAlignment="Top" Width="321"/>

Separate View not updating from background worker Mvvm

I am having issues updating a separately opened window's progress bar from a background worker inside another class.
The program execution goes like this:
MainWindow loads
Click button to do some work and open a popup
progress bar (newly opened window)
Background worker does work
and reports progress to popup progress bar
Popup progress bar
hopefully updates.
The progress bar Value is bound to a property, which in the step-through debugger, looks to be getting updated okay by the background worker. These changes just are not reflected on the popup progress bar view. However, the binding is not broken because if I manually try and set the property value for the progress bar it works fine.
Furthermore, when I put the progress bar inside the initially started MainWindow view it updates fine. Any suggestions??
Here is the some code:
MainWindowViewModel
public class MainWindowViewModel: BaseViewModel
{
private void PerformSomeAction()
{
var popUpProgressBar = new PopUpProgressBarViewModel();
popUpProgressBar.Show(popUpProgressBar);
var worker = new BackgroundWorker { WorkerReportsProgress = true };
worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
{
if (args.ProgressPercentage != popUpProgressBar.Progresser)
{
Progresser = args.ProgressPercentage;
popUpProgressBar.Progresser = args.ProgressPercentage;
}
};
worker.DoWork += delegate
{
for (int i = 0; i < 101; i++)
{
worker.ReportProgress(i);
System.Threading.Thread.Sleep(10);
}
MessageBox.Show("Done");
};
worker.RunWorkerAsync();
}
private int _progresser;
public int Progresser
{
get { return _progresser; }
set
{
if (_progresser == value) return;
_progresser = value;
OnPropertyChanged("Progresser");
}
}
private RelayCommand _startProcessing; //set private member
public ICommand StartProcessing //public field used by xaml binding
{
get
{
return _startProcessing = MakeCommandSafely(_startProcessing, () => PerformSomeAction());
}
}
}
PopUpProgressBarViewModel
public class PopUpProgressBarViewModel : BaseViewModel
{
private PopUpProgressBar _popUpProgressBar;
public void Show(PopUpProgressBarViewModel context)
{
_popUpProgressBar = new PopUpProgressBar {DataContext = context};
_popUpProgressBar.Show();
}
private int _progresser;
public int Progresser
{
get { return _progresser; }
set
{
if (_progresser == value) return;
_progresser = value;
OnPropertyChanged("Progresser");
}
}
}
For full solution file (so you can see whats happening), see here
As #Doug said, since you are already setting the DataContext:
_popUpProgressBar = new PopUpProgressBar {DataContext = context};
You can change the PopUpProgressBar to
<Window x:Class="OpeningWindow_With_ProgressBar.View.PopUpProgressBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ViewModel="clr-namespace:OpeningWindow_With_ProgressBar.ViewModel" Title="PopUpProgressBar" Height="150" Width="300">
<Grid>
<StackPanel>
<Label FontWeight="Bold">Loading Something</Label>
<ProgressBar Minimum="0" Maximum="100" Margin="0,10,0,0" Height="25px" Width="250px" Value="{Binding Path=Progresser, Mode=OneWay}"></ProgressBar>
<TextBlock Margin="10,10,0,0" Text="Details of loading..."></TextBlock>
</StackPanel>
</Grid>
You are creating two PopUpProgressBarViewModels. You've got one that's being created as a resource inside PopUpProgressBar.xaml, and the other one is being created in MainWindowViewModel (line 18).
Your XAML is bound to the one created inside PopUpProgressBar.xaml, while the one that you're updating is the one created in MainWindowViewModel.
If you can pare it down so only one is created, that should solve your problem.

Categories