c# - 在viewmodel的构造函数中调用async方法加载数据有警告

标签 c# .net wpf asynchronous async-await

我的 View 包含一个 ListView,它显示来自互联网的一些数据,我创建了一个异步方法来加载数据并在我的 View 模型的构造函数中调用该方法。它有一个警告提示我现在使用 await 关键字。

在构造函数中异步加载数据的任何其他解决方案?

最佳答案

有几个模式可以应用,所有这些都在 Stephan Cleary 的帖子中提到过。

但是,让我提出一些不同的建议:

由于您在 WPF 应用程序中,我会使用 FrameworkElement.Loaded事件并将其绑定(bind)到 ViewModel 中的 ICommand。有界命令将是 Awaitable DelegateCommand可以等待。我也会利用 System.Windows.Interactivity.InvokeCommandAction

查看 XAML:

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

View 模型:

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
    }
}

关于c# - 在viewmodel的构造函数中调用async方法加载数据有警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24572064/

相关文章:

c# - Winforms 中的事件和 WPF 中的命令有什么区别?

c# - WPF:MVVM 上窗口之间的通信

c# - 如何强制平滑呈现 WPF 控件?

wpf - 什么 MVVM 框架适合?

c# - 这叫适配器? + 适配器与装饰器

c# - 如何在 C# 中复制数组的值 n 次

jquery - 按需绑定(bind) KendoUI 下拉列表

c# - 尝试使用 EPPlus 在服务器上读取 Excel 文件,但不能通过浏览器

c# - 匿名管道是去这里的正确方法吗?

c# - 在 MVC 编辑操作 {HTTP POST} 中使用 UpdateModel 与 Request.Form 集合