调用异步方法在视图模型的构造函数加载数据具有警示 [英] Calling async method to load data in constructor of viewmodel has a warning
问题描述
我的观点包含了显示来自互联网的一些数据一个ListView,我创建了一个异步方法加载数据,并调用视图模型我的构造方法。它有一个警告,提示我现在用的等待关键字。
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:
既然你是在一个WPF应用程序,我会使用<$c$c>FrameworkElement.Loaded$c$c>事件并将其绑定到的ICommand
里面你视图模型。有界命令将是一个 Awaitable DelegateCommand
可以期待。我还将利用<一个href=\"http://msdn.microsoft.com/en-us/library/system.windows.interactivity.invokecommandaction%28v=ex$p$pssion.40%29.aspx\"><$c$c>System.Windows.Interactivity.InvokeCommandAction$c$c>
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
查看XAML:
<Grid>
<interactivity:Interaction.Triggers>
<interactivity:EventTrigger EventName="Loaded">
<interactivity:InvokeCommandAction Command="{Binding MyCommand}"/>
</interactivity:EventTrigger>
</interactivity:Interaction.Triggers>
</Grid>
视图模型:
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
}
}
这篇关于调用异步方法在视图模型的构造函数加载数据具有警示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!