Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling async method to load data in constructor of viewmodel has a warning

My view contains a ListView which display some data from internet, I create an async method to load data and call the method in my viewmodel's constructor. It has an warning prompt me now use await keyword.

Any other solution to load data asynchronously in the constructor?

like image 541
Allen4Tech Avatar asked Jul 04 '14 10:07

Allen4Tech


1 Answers

There are a couple of patterns which can be applied, all mentioned in the post by Stephan Cleary.

However, let me propose something a bit different:

Since you are in a WPF application, i would use the FrameworkElement.Loaded event and bind it to a ICommand inside you ViewModel. The bounded command would be an Awaitable DelegateCommand which can be awaited. I'll also take advantage of System.Windows.Interactivity.InvokeCommandAction

View XAML:

<Grid>
 <interactivity:Interaction.Triggers>
     <interactivity:EventTrigger EventName="Loaded">
         <interactivity:InvokeCommandAction Command="{Binding MyCommand}"/>
     </interactivity:EventTrigger>
 </interactivity:Interaction.Triggers>
</Grid>

ViewModel:

public class ViewModel
{
    public ICommand MyCommand { get; set; }

    public ViewModel()
    {
        MyCommand = new AwaitableDelegateCommand(LoadDataAsync);
    }

    public async Task LoadDataAsync()
    {
        //await the loading of the listview here
    }
}
like image 198
Yuval Itzchakov Avatar answered Sep 28 '22 11:09

Yuval Itzchakov