MVVM Passing data between two views / view models

2019-07-04 12:04发布

问题:

I have two Pages:

  1. Page 1
  2. Page 2

and two ViewModels with the same properties:

  1. ViewModel1
    Properties:
    • FirstName1
    • LastName1
  2. ViewModel2
    Properties:
    • FirstName2
    • LastName2

Now I want to pass data(properties) between ViewModel1 to ViewModel2, and retrive this data on the Page 2. How do I achieve this?

回答1:

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.



回答2:

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


回答3:

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.



标签: c# asp.net mvvm