Reputation: 3865
i have a ViewModel with an ObservableCollection, i have a long function that i will use to update the ObservableCollection items however the function is so long and i don't want to put it inside the ViewModel.
i want to do the updates directly on the ObservableCollection so that i can see the changes on my view while the process is running.
i thought about the followig
there will be alot of different functions that will work on this collection, in such cases what is the best programing practice?
Upvotes: 0
Views: 917
Reputation: 3004
If you are processing the data and then passing the processed data to the View then I think the below option should be one possible solution.
The below solution will process the data while the view is also notified of the change simultaneously.
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;
}
}
The DoSomething method can be defined in some other class outside the ViewModel.
I hope this helps.
Upvotes: 1