Edu Borras
Edu Borras

Reputation: 3

How to pass value in Viewmodel to other ViewModel with mvvmcross UWP

I would like to know how to send the value of a view model to another viewmodel using mvvcross and uwp

Does anyone know how to do it?

Thanks,

Upvotes: 0

Views: 543

Answers (1)

Martijn00
Martijn00

Reputation: 3559

You can use the IMvxNavigationService to pass and return objects. The full documentation is at: https://www.mvvmcross.com/documentation/fundamentals/navigation?scroll=26

In your ViewModel this could look like:

public class MyViewModel : MvxViewModel
{
    private readonly IMvxNavigationService _navigationService;
    public MyViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;
    }

    public override void Prepare()
    {
        //Do anything before navigating to the view
    }

    public async Task SomeMethod()
    {
        _navigationService.Navigate<NextViewModel, MyObject>(new MyObject());
    }
}

public class NextViewModel : MvxViewModel<MyObject>
{
    public override void Prepare(MyObject parameter)
    {
        //Do anything before navigating to the view
        //Save the parameter to a property if you want to use it later
    }

    public override async Task Initialize()
    {
        //Do heavy work and data loading here
    }
}

Using a IMvxMessenger you can send values without have a connection: https://www.mvvmcross.com/documentation/plugins/messenger?scroll=1446

public class LocationViewModel
    : MvxViewModel
{
    private readonly MvxSubscriptionToken _token;

    public LocationViewModel(IMvxMessenger messenger)
    {
        _token = messenger.Subscribe<LocationMessage>(OnLocationMessage);
    }

    private void OnLocationMessage(LocationMessage locationMessage)
    {
        Lat = locationMessage.Lat;
        Lng = locationMessage.Lng;
    }

    // remainder of ViewModel
}

Upvotes: 1

Related Questions