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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With