简体   繁体   中英

Update UI Thread from ViewModel

I am trying to execute the simple action of updating a progress bar on my UI inside of a loop by using a BackgroundWorker . I don't know what I'm doing wrong. Any help is greatly appreciated.

private void ProcessButtonClickAction(object param)
{
   BackgroundWorker BGWUpdateUi = new BackgroundWorker();

   BGWUpdateUi.ProgressChanged += (sender, args) =>
   {
       ProgressBarValue += args.ProgressPercentage;
       ((SelectedDwgFile)args.UserState).Status = "Completed";
   };

   BGWUpdateUi.WorkerReportsProgress = true;

    foreach(var obj in FileList)
    {
        Thread.Sleep(250);
        BGWUpdateUi.ReportProgress(pbvalueIncrement, obj);
    }
}

The collection is an ObservableCollection and ProgressBarValue is bound to the value of the progress bar.

I have looked at several of examples and no matter which one I try - BackgroundWorker , Dispatcher - they all update after the loop.

Put the part that you want to run in the background, into the DoWork method, and then call RunWorkerAsync :

private void ProcessButtonClickAction(object param)
{
   BackgroundWorker BGWUpdateUi = new BackgroundWorker()

   BGWUpdateUi.DoWork += (sender, args) =>
   {
       foreach (var obj in FileList)
       {
           Thread.Sleep(250);
           obj.Status = "Completed";
           ProgressBarValue += pbvalueIncrement;
       }
   };
   BGWUpdateUi.RunWorkerAsync();
}

Also, make sure to dispatch UI-related updates back to the UI thread (otherwise you will get a cross-thread access exception).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM