如果您正在處理數據,然後將處理的數據傳遞給視圖,那麼我認爲下面的選項應該是一個可能的解決方案。
以下解決方案將處理數據,同時視圖也會同時通知更改。
public class MyViewModel : INotifyPropertyChanged
{
private ObservableCollection<string> _unprocessedData = new ObservableCollection<string>();
private ObservableCollection<string> _processedData = new ObservableCollection<string>();
private static object _lock = new object();
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<string> Collection { get { return _processedData; } }//Bind the view to this property
public MyViewModel()
{
//Populate the data in _unprocessedData
BindingOperations.EnableCollectionSynchronization(_processedData, _lock); //this will ensure the data between the View and VM is not corrupted
ProcessData();
}
private async void ProcessData()
{
foreach (var item in _unprocessedData)
{
string result = await Task.Run(() => DoSomething(item));
_processedData.Add(result);
//NotifyPropertyChanged Collection
}
}
private string DoSomething(string item)
{
Thread.Sleep(1000);
return item;
}
}
DoSomething方法可以在ViewModel之外的其他類中定義。
我希望這會有所幫助。