Dhruv Gohil
Dhruv Gohil

Reputation: 842

MvvmCross passing data from One viewmodel to another viewmodel

I am working on Xamarin Android Application.I am using MvvmCross pattern for ViewModels.

Now,I want to pass data from one ViewModel to another viewmodel but don't want to navigate to that ViewModel. Instead of navigating to that ViewModel I want to navigate to another ViewModel.

e.g: I have three ViewModels V1,V2 and V3.Now I want to pass data from V1 to V2 but want to navigate to V3.

Is that possible ?

Upvotes: 0

Views: 1352

Answers (3)

xleon
xleon

Reputation: 6365

An alternative to the mentioned messenger plugin I would suggest to save the data you need to share in a "service", being the service a singleton class managed by MvvmCross:

CreatableTypes()
    .EndingWith("Service")
    .AsInterfaces()
    .RegisterAsLazySingleton();

In your view models you can use that singleton just by adding it to the constructor:

public WhateverViewModel(IService service)

The service will be singleton so your data will persists over the application live cycle.

So, in one of your view models you could do:

service.SharedData = new SharedData();

In another view model:

this.data = service.SharedData

Upvotes: 0

jsbeckr
jsbeckr

Reputation: 1193

The easiest way to do this is using the Messenger Plugin from MvvmCross.You can subscribe a certain kind of message in V2 and publish that message in V1 and then navigate to V3 in a seperate step.

// subscribing to a certain message type
this.logoutToken = this.messenger.Subscribe<LogoutMessage>(this.HandleLogoutMessage);

// Creating and sending a message
var logoutMessage = new LogoutMessage(this, "You have been logged out.");
this.messenger.Publish(logoutMessage);

Note: It is important to assign the MessageToken to a member variable (like in the other answer), because otherwise it will get cleaned up by the garbage collector.

Upvotes: -1

Martijn00
Martijn00

Reputation: 3559

Look into the MvvmCross Messenger to do this: https://github.com/MvvmCross/MvvmCross-Plugins/tree/master/Messenger

You need to subscribe for something on your viewmodel:

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: 3

Related Questions