如何从另一个类访问变量以更新ViewModel

时间:2019-08-05 01:24:11

标签: c# .net wpf mvvm

我有一个带有ProgrressBar的应用程序。 我也有一个充当DownloadService的类,因为它已在多个ViewModel中使用。

如您所见,函数DownloadData模拟它的下载内容,并以百分比为单位跟踪已下载的数据总量,范围为0-100。

如何在不传入MainWindowViewModel作为参数的情况下使我的ProgressBar获得与totalDownloaded相同的值。

MainWindow

<Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
    <StackPanel>
        <ProgressBar Height="25"
                     Maximum="100"
                     Value="{Binding ProgressValue}"/>
        <Button HorizontalAlignment="Center"
                Width="100" Height="25"
                Content="Start"
                Command="{Binding StartDownloadCommand}"/>
    </StackPanel>

MainWindowViewModel

class MainWindowViewModel : ObservableObject
    {
        private int _progressValue;

        public int ProgressValue
        {
            get { return _progressValue; }
            set
            {
                _progressValue = value;
                OnPropertyChanged();
            }
        }

        DownloadService ds = new DownloadService();

        public RelayCommand StartDownloadCommand { get; set; }

        public MainWindowViewModel()
        {
            StartDownloadCommand = new RelayCommand(o => { ds.DownloadData(); }, o => true);
        }
    }

DownloadService

 class DownloadService
    {
        public void DownloadData()
        {
            int totalDownloaded = 0;

            for (int i = 0; i < 101; i++)
            {
                totalDownloaded++;
                Console.WriteLine(totalDownloaded);
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

参考 Progress<T> Class

  

提供一个IProgress<T>,它为每个报告的进度值调用回调。

重构服务以依赖于passingParameter["user_id"] = userID 抽象,并使用它来报告进度

IProgress<int>

视图模型可以将class DownloadService { public void DownloadData(IProgress<int> progress = null) { int totalDownloaded = 0; for (int i = 0; i < 101; i++) { totalDownloaded++; progress?.Report(totalDownloaded); // ?. just in case Console.WriteLine(totalDownloaded); } } } 传递给服务以获取进度更新的报告。

Progress<int>

明确取决于public MainWindowViewModel() { StartDownloadCommand = new RelayCommand(o => { var progress = new Progress<int>(value => ProgressValue = value); ds.DownloadData(progress); }, o => true); } ,避免了将视图模型与服务紧密耦合的情况。