2

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.

I found some solutions to implement this using background-worker class. For some reasons i am not allowable to use background worker.

Does any one have any suggestions on how to implement this?

Thanks in advance

Subin
  • 65
  • 10
  • Implementing Progress bar in an MVVM application is not a big deal, but what you have tried so far, and what issue are u facing to implement? – Vimal CK May 15 '15 at 07:06
  • Depends very much on _Progress of What_. – Henk Holterman May 15 '15 at 07:16
  • Does it means that you're not allowed to use background threads at all or just the background worker? If that's the case your UI will lock up until the whole operation has finished. – XAMlMAX May 15 '15 at 10:10
  • @VimalCK the problem is not updating progressbar. How can i update in a thread manner. – Subin May 15 '15 at 10:18
  • @XAMlMAX i am working on an ArcGiS solution which doesn't support bacground-worker. that's my problem. – Subin May 15 '15 at 10:21
  • Then use @HenkHolterman solution. When you trigger your action in your `VM` update the value of the `ProgressValue`, remember that the `ProgressValue` Needs to implement `INotifyPropertyChanged`. Your UI will become unresponsive during the execution though. – XAMlMAX May 15 '15 at 10:24
  • i need my UI to be responsive during the process. – Subin May 15 '15 at 10:26

2 Answers2

2

I would prefer Task over background workers. Anyway, here's a simple implementation of progress bar.

<ProgressBar Value="{Binding ProgressValue}" Maximum="100" Height="20" />

 

public MainViewModel()
{
    Task.Run(() =>
        {
            while (true)
            {
                ProgressValue++;
                Thread.Sleep(250);
            }
        });
    }

    public int ProgressValue
    {
        get { return _progressValue; }
        set { _progressValue = value; OnPropertyChanged(); }
    }
}
Mikko Viitala
  • 8,066
  • 4
  • 37
  • 57
1

The basics are very simple.

View:

 <ProgressBar Value="{Binding ProgressValue}" />

ViewModel:

 public double ProgressValue { get/set with INPC }

But the remaining challenge is to set the ViewModels ProgressValue from a non-blocking process in a thread-safe manner.

Your question lacks the details to help with that.

Henk Holterman
  • 236,989
  • 28
  • 287
  • 464
  • the problem with this solution is that it make my UI unresponsive. – Subin May 15 '15 at 10:29
  • Yes, I said 'non blocking'. But for the how of that you need to be more specific. – Henk Holterman May 15 '15 at 11:06
  • 1
    Bindings in 4.0 and above automatically marshal INPC events onto the UI thread, so you can set the property values from a background thread without worry. –  May 15 '15 at 14:01