Home > other >  WPF Progress bar not updating while calling the method from another class
WPF Progress bar not updating while calling the method from another class

Time:08-30

Trying to call the mainwindow update progressbar method from another class. The progressbar is not getting updated.

XAML Code

<ProgressBar x:Name="ProgressSplit" Margin="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center"
             Grid.Row="11" Grid.Column="2" Minimum="0" Maximum="100" Foreground="#ffe600"
             Width="700" Height="30" />
<TextBlock x:Name="txtProgressText" Text="{Binding ElementName=ProgressSplit, Path=Value, StringFormat={}{0:0}%}" Grid.Row="11" Grid.Column="2"
           HorizontalAlignment="Center" VerticalAlignment="Center" />

MainWindow.xaml code

private delegate void UpdateProgressBarDelegate(DependencyProperty dp, Object value);
public void UpdateProgressBar(double value)
{
     var updatePbDelegate = new UpdateProgressBarDelegate(ProgressSplit.SetValue);
     Dispatcher.CurrentDispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { RangeBase.ValueProperty, value });
}

Trying to call the public method from another class to update the progress bar

var mainWindow = (MainWindow)Application.Current.MainWindow;
mainWindow.UpdateProgressBar(20);

CodePudding user response:

I'm not sure what the specific problem with your code is, but that is not the recommended way to handle progress. One problem is that you rely on a public property of the main window, so you have a tight coupling between your UI and your worker method.

Typically you should do something like

public async void OnButtonpress(){
    var progress = new Progress<int>(Update);
    void Update(int value) => ProgressSplit.Value = value;
    try{
       await Task.Run(() => WorkerMethod(progress));
    }
    catch{
       ...
    }
}
public void WorkerMethod(IProgress<int> progress){
   // on background thread
   for(int i = 0; i< 100; i  ){
        // do work
        progress.Report(i);
   }
}

The progress class will take care of updating the progress bar on the UI thread. This helps decouple the UI from the worker method. This pattern is also amenable to adding things like cancellation etc. Just remember to take care to set the maximal value of the progress bar. Personally I prefer to always use a double to report progress, where 1.0 represent a completed task, so you can always report i / totalNumberOfItems.

  • Related