我的视图包含一个 ListView,它显示来自互联网的一些数据,我创建一个异步方法来加载数据并在我的视图模型的构造函数中调用该方法。它有一个警告提示我现在使用await关键字。
还有其他解决方案可以在构造函数中异步加载数据吗?
有几种可以应用的模式,所有这些都在 Stephan Cleary 的帖子中提到。
然而,让我提出一些不同的建议:
由于您在 WPF 应用程序中,我将使用FrameworkElement.Loaded http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.loaded(v=vs.110).aspx事件并将其绑定到ICommand
在你的 ViewModel 里面。有界命令将是Awaitable DelegateCommand http://jake.ginnivan.net/awaitable-delegatecommand/这是可以期待的。我也会利用System.Windows.Interactivity.InvokeCommandAction http://msdn.microsoft.com/en-us/library/system.windows.interactivity.invokecommandaction(v=expression.40).aspx
查看 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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)