简体   繁体   中英

Xamarin.Forms MVVM - How to send data from an async function to ViewModel

I have an issue with sending data from an async function started by a button press to the page's ViewModel, which will be used to update it - the issue being I don't know how to do it. What would be the best way send the data once the async function finishes? I'm just starting to learn Xamarin and MVVM, as I'm mostly asking for pointers to resources to learn how to do it - I feel like I missed some important parts.

What I've tried is MessagingCenter (which doesn't seem to work beteen Model and ViewModel) and ObservableCollection (which seems like it should be the solution, but I don't really know how to get it to work in this scenario).

I typically have the button call a Command instead of trying to have an async function call the view model. A command is something like the below:

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

You would then bind it like this

<Button Text="TEXT" Command="{Binding NavigateCommand }" />

All of this is explained in more detail here: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/commanding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM