I'd like to load my viewmodel after a page has loaded but I can't seem to figure out how to do this.
Here's the viewModel methods where both methods inside LoadViewModel are long running async methods:
public async Task LoadViewModel()
{
await GetAllTiles();
await UpdateAllScenarioCardsAsync();
}
In the view I'm trying something like this:
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
var viewModel = DataContext as StatsViewModel;
if (viewModel != null)
{
var statsViewModel = viewModel;
await statsViewModel.LoadViewModel();
}
}
For some reason the LoadViewModel() method blocks the entire UI even if I remove the awaits for GetAllTiles() and UpdateAllScenarioCardsAsync()... The NavigationHelper_LoadState method is run before the page is loaded so I've tried registering LoadViewModel() to the Loaded event of the page but I can't seem to get it to work.
EDIT Here is my UpdateAllScenarioCardsAsync() class. UpdateTotalTilesAsync() and UpdataTodayTilesAsync() have await statements inside the code as well but it still blocks the UI. I used closedScenario because I thought the issue could be closing over a variable over the wrong scope like answered in this question, but still now luck. I'm tempted to think it has something to do with the foreach loop because I have successfully done this elsewhere in my solution and it doesn't block the UI thread, but that code had no foreach loop.
private async Task UpdateAllScenarioCardsAsync()
{
IsPending = true;
try
{
// Load all of the scenario cards
foreach (var scenario in _scenariosList)
{
var closedScenario = scenario;
var data = new ScenarioDataCard(closedScenario);
await UpdateTotalTiles(data);
await UpdateTodayTestedTiles(data);
ScenarioDataCards.Add(data);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
IsPending = false;
}
}