In this simple example, we will see how to create and manipulate the ProgressBar control from WPF in a MVVM way.

Let’s start with the View in XAML:

<Window x:Class="ProgressBar_Demo.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" Title="{Binding Title}" Height="350" Width="525"> <Window.Resources> <BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" /> </Window.Resources> <Grid> <StackPanel Orientation="Vertical"> <Button Margin="30" Width="70" Command="{Binding StartWorkCommand}" Content="Start" /> <!--PROGRESS BAR WITH TEXT--> <Grid Margin="20" Visibility="{Binding ProgressVisibility, Converter={StaticResource booleanToVisibilityConverter}}"> <ProgressBar Margin="20" Height="20" Width="150" Value="{Binding CurrentProgress, Mode=OneWay}" /> <TextBlock Text="{Binding CurrentProgress, StringFormat={}{0:0}%}" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </StackPanel> </Grid> </Window>
Code language: HTML, XML (xml)

And now the ViewModel:

using Prism.Commands; using Prism.Mvvm; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; namespace ProgressBar_Demo.ViewModels { public class MainWindowViewModel : BindableBase { #region Properties private string _title = "ProgresBar Demo"; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } private readonly BackgroundWorker _worker; private ICommand _startWorkCommand; public ICommand StartWorkCommand { get { return _startWorkCommand ?? (_startWorkCommand = new DelegateCommand(() => _worker.RunWorkerAsync(), () => !_worker.IsBusy)); } } private int _currentProgress; public int CurrentProgress { get { return _currentProgress; } private set { SetProperty(ref _currentProgress, value); } } private bool _progressVisibility; public bool ProgressVisibility { get { return _progressVisibility; } set { SetProperty(ref _progressVisibility, value); } } #endregion public MainWindowViewModel() { _worker = new BackgroundWorker(); _worker.DoWork += DoWork; _worker.WorkerReportsProgress = true; _worker.ProgressChanged += ProgressChanged; ProgressVisibility = false; } private void DoWork(object sender, DoWorkEventArgs e) { ProgressVisibility = true; for (int i = 0; i <= 100; i++) { //Simulate a long running task Thread.Sleep(50); //Reports the progress (sender as BackgroundWorker).ReportProgress(i); } ProgressVisibility = false; } private void ProgressChanged(object sender, ProgressChangedEventArgs e) { CurrentProgress = e.ProgressPercentage; if (CurrentProgress == 100) ProgressVisibility = false; } } }
Code language: C# (cs)

Happy coding! 🙂