I do not know how to accurately formulate the question.
There is a function that performs some action. It is located in the "class library". I connect this library to my application. I run this function and want the ProgressBar display the progress of this procedure from the library. How to implement this correctly in the MVVM approach?
UPD: Here is an example of the Vlad method: Function in the library:
using System; namespace ClassLib { public static class Service { public static void Foo(IProgress<int> progress) { progress.Report(1); string s; for (int i = 1; i <= 99; i++) { for (int j = 0; j <= 50000; j++) s = j.ToString(); progress.Report(i); } progress.Report(100); } } } ViewModel:
public class MainWindowViewModel: INotifyPropertyChanged { private int _progr; public int Progress { get { return _progr; } set { _progr = value;OnPropertyChanged("Progress"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); public void StartFoo() { Service.Foo(new Progress<int>(persent => Progress = persent)); } } View: XAML
<Window.DataContext> <vm:MainWindowViewModel x:Name="windowVM"/> </Window.DataContext> ... <ProgressBar Value="{Binding Progress, UpdateSourceTrigger=PropertyChanged}"/> c # code:
private void button_Click(object sender, RoutedEventArgs e) { MainWindowViewModel vm = (MainWindowViewModel)this.DataContext; vm.StartFoo(); } The process is displayed as follows: 0 pause 100%.