c# - Xamarin.Forms MVVM - 如何将数据从异步函数发送到 ViewModel
问题描述
我在将数据从由按下按钮启动的异步函数发送到页面的 ViewModel 时遇到问题,该视图模型将用于更新它 - 问题是我不知道该怎么做。异步功能完成后发送数据的最佳方式是什么?我刚刚开始学习 Xamarin 和 MVVM,因为我主要是在寻求资源的指针来学习如何去做——我觉得我错过了一些重要的部分。
我尝试过的是MessagingCenter(它似乎在 Model 和 ViewModel 之间不起作用)和ObservableCollection(它似乎应该是解决方案,但我真的不知道如何让它在这种情况下工作)。
解决方案
我通常让按钮调用命令,而不是尝试让异步函数调用视图模型。命令类似于以下内容:
public partial class MainViewModel
{
public MainViewModel ()
{
InitializeComponent();
NavigateCommand = new Command<Type>(
async (Type pageType) =>
{
Page page = (Page)Activator.CreateInstance(pageType);
await Navigation.PushAsync(page);
});
BindingContext = this;
}
public ICommand NavigateCommand { private set; get; }
}
然后你会像这样绑定它
<Button Text="TEXT" Command="{Binding NavigateCommand }" />
所有这些都在这里更详细地解释:https ://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/commanding
推荐阅读
- python - TypeError:int() 参数必须是字符串或数字,而不是“NoneType”
- postgresql - 我什么时候需要将值转换为日期?
- java - 为什么我不能编辑未保存来电号码的通话记录?
- mysql - 数据库 utf8mb4_unicode_ci 不保存完整的表情符号
- c# - 将编组字符串崩溃到 .NET
- java - 如何将 utf-8 转换为字符串
- node.js - 从 Node JS 缓冲区读取 UINT 128
- ruby-on-rails - 如何使用单个 SQL 查询有效地从 activerecord 中检索对象组?
- android - 最后已知位置始终为 0
- python - 有没有办法在类似于合并的第一个非空变量上合并 DataFrame?