簡體   English   中英

如何從另一個類訪問變量以更新我的ViewModel

[英]How do I access a variable from another class to update my ViewModel

我有這個應用程序,上面有一個ProgrressBar 我還有一個充當DownloadService的類,因為它在多個ViewModel中使用。

正如您所看到的, DownloadData函數模擬它下載的內容,並以百分比形式跟蹤已下載的數據總量,它從0到100。

如何使我的ProgressBar獲取與totalDownloaded相同的值,而不將MainWindowViewModel作為參數傳遞。

主窗口

<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);
            }
        }
    }

參考Progress<T> Class

提供IProgress<T> ,為每個報告的進度值調用回調。

重構服務以依賴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);
        }
    }
}

View模型可以將Progress<int>傳遞給服務以獲取進度更新的報告。

public MainWindowViewModel() {
    StartDownloadCommand = new RelayCommand(o => { 
        var progress = new Progress<int>(value => ProgressValue = value);
        ds.DownloadData(progress); 
    }, o => true);
}

顯式取決於IProgress<int>避免必須將視圖模型緊密耦合到服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM