如果您正在处理数据,然后将处理后的数据传递给视图,那么我认为以下选项应该是一种可能的解决方案。
下面的解决方案将处理数据,同时也会通知视图更改。
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 之外的某个其他类中定义。
我希望这有帮助。