I have two Pages:
- Page 1
- Page 2
and two ViewModels with the same properties:
- ViewModel1
Properties:
- ViewModel2
Properties:
Now I want to pass data(properties) between ViewModel1 to ViewModel2, and retrive this data on the Page 2.
How do I achieve this?
You could take a look at MVVMLight's Messenger. Here's is a tutorial that could guide you on your way. Basically, the idea is to use a messenger that's independent from your Views/ViewModels to send messages from/to them. Your Views/ViewModels register and send specific messages that contain properties values you want to pass along.
Your page could be constructed like so:
public class Page2 {
public ViewModel1 VM1;
public Page2() {
VM1 = new ViewModel1(new ViewModel2());
}
}
Your ViewModel1
could look like so, with pass-through properties:
public class ViewModel1 : Person {
private ViewModel2 _vm2;
public ViewModel1(ViewModel2 vm2) {
_vm2 = vm2;
}
public override string FirstName {
get { return _vm2.FirstName; }
}
public override string LastName {
get { return _vm2.LastName; }
}
}
We assume your ViewModel2
has some business logic or something
public class ViewModel2 : Person {
//Etc
}
Both inherit from the same base class:
public abstract class Person {
public abstract string FirstName { get; }
public abstract string LastName { get; }
}
You can either go with a parent ViewModel that both viewmodels inherit from or an Event Aggregator. Here is a simple one using Reactive Extensions.