gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:54:45 27 4
gpt4 key购买 nike

我的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com