When last we left off, we were loading the data for the ViewModel inside its constructor – a bad idea, because the data loading is done asynchronously, and constructors can’t be made async. So we need to find a better way to do that.
First off I want to factor the process of loading the data out to its own method inside my OverviewVM class:
With this public method I’ve got more options on handling the data. So the question is: do I really need to load the data right when my View Model is constructed? Actually, no. I don’t need the data until my View appears – and the OnAppearing() method can be made async to accommodate the asynchronous nature of data loading.
Because I need a reference to my View Model in OnAppearing(), I’m storing it in a field for now. Later on, when we get to decoupling our classes, that’s going to be done a better way, but for now this will do the job.
Except that there’s a little problem now. Because the data we’re binding to is not already in place when the page appears, our list of ToDo’s is empty. We need to explicitly tell our View that our collection of ToDoItems has changed.
I could do this by making my ViewModel implement the INotifyPropertyChanged interface – but fortunately MVVMLight already has a base class in place that will handle all of that for me. All I need to do is to make my View Model inherit from ViewModelBase and use ViewModelBase’s Set method, which handles both the assignment and notification for me.
The resulting View Model now looks like this:
So, another hurdle jumped. The code is slowly starting to look better, but still suffers from tight coupling. More on this next!