简体   繁体   中英

Data sharing between multiple ViewModels

Further to my question how can I bind Bing Pushpins from multiple models?

This is pretty new to me and I have been searching through the web but there seem so many different approaches to MVVM and then adding in WP7 and I have got a bit confused

I am now trying to work out the best way to share data between ViewModels or even if that is the best way to do it.

What I mean is I have, for example

My models: PeopleModel, BuildingModel My ViewModels: PeopleViewModel, BuildingViewModel (which contain Observable collections of the model)

At the moment a Timer is used to update the lists from a Webservice. The ViewModel because it is static is able to be updated during the lifetime of the application. I am not sure this is the most sensible approach though but I need some form of background sync to fit the requirements.

The People and Building contain a location but not anything regarding what image it should display as a pushpin. So I was thinking if I had a my map view containing a MapViewModel that is linked somehow to the ViewModels but I am not sure how you would do this.

I looked at MVVMLight and it seems you can register the ViewModels at start so it would be possible to add links to the other ViewModels and not worry about the lifetimes of them?

However given that there is extra information within the Models that the Map isn't interested in I wonder if is better to have a self-contained MapViewModel that contains lists of Custom pushpins of some type (so PeoplePushpins, BuildingPushpins). If I go this route I would like to know how you update the MapViewModel from data updated in the other Models.

What I mean is the running timer in PersonViewModel detects a change in the list, so updates its own list. I the need to send notification to the Map that there is an update which then will update itself from that.

Any help/advice gratefully received.

With MVVMLight you can use messaging to send data between models:

//build class to send as message  
public class AddPushPinMessage
{
    public PushPin PushPin { get; set; }
}

public class ReceivingViewModel
{
  public ReceivingViewModel()
  {
     Messenger.Default.Register<AddPushPinMessage>(this, (m) => AddPushPin(m));
  }

  void AddPushPin(AddPushPinMessage msg)
  {
     //handle message
  }
}

public class SendingViewModel
{
  private object SendPushPin(PushPin key)
  { 
    Messenger.Default.Send<AddPushPinMessage>(new SetPushPinMessage() { PushPin = key });

    return null;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM