首页 > 解决方案 > Xamarin.Forms MVVM - 如何将数据从异步函数发送到 ViewModel

问题描述

我在将数据从由按下按钮启动的异步函数发送到页面的 ViewModel 时遇到问题,该视图模型将用于更新它 - 问题是我不知道该怎么做。异步功能完成后发送数据的最佳方式是什么?我刚刚开始学习 Xamarin 和 MVVM,因为我主要是在寻求资源的指针来学习如何去做——我觉得我错过了一些重要的部分。

我尝试过的是MessagingCenter(它似乎在 Model 和 ViewModel 之间不起作用)和ObservableCollection(它似乎应该是解决方案,但我真的不知道如何让它在这种情况下工作)。

标签: c#xamarinxamarin.formsmvvm

解决方案


我通常让按钮调用命令,而不是尝试让异步函数调用视图模型。命令类似于以下内容:

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


推荐阅读