Steven Gazo M.
Steven Gazo M.

Reputation: 107

Send Data Between ViewModels | MVVM | .net Maui

I'm building an app using .net Maui (the app is for android and windows) and i'dont have experience in mobile Development😅

I wanna know how i can pass data (objects) between 2 ViewModels.

Actually i' using MessagingCenter to send data from the ViewModel A and suscribe in the ViewModel B, but i'dont know is this is the best way to do it .

In the first versions i send the data in the constructor of the ViewModel Class using a parameter defined in the views, but i generate a dependency between the views and the viewmodels

Upvotes: 2

Views: 2784

Answers (1)

Giacomo
Giacomo

Reputation: 11

Using Shell Navigation you can pass and receive primitive/object data between ViewModels. I leave you a small example:

Step 1 in first ViewModel (passing data):

public void GoToPage2() {

    var navigationParameters = new Dictionary<string, object>
    {
        { "Yourkey", YourObject },
    };

    await Shell.Current.GoToAsync(nameof(Page2),false,navigationParameters);
}

Step 2 in second ViewModel (receiving data):

public class Page2ViewModel : INotifyPropertyChanged,IQueryAttributable {

  public YourObjectType YourObject { get; private set; }
    
  public void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        YourObject = query["YourKey"] as YourObjectType;
        OnPropertyChanged("YourObject");
    }
    
}

Important: Use IQueryAttributable in your class.

Here the documentation what helped me. .NET MAUI Shell Navigation

Upvotes: 0

Related Questions