开发者

Data sharing between multiple ViewModels

开发者 https://www.devze.com 2023-04-02 11:36 出处:网络
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 th

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开发者_StackOverflow社区 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;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消