Phil
Phil

Reputation: 601

Update ObservableCollection between Viewmodels

I have shared an observableCollection between two ViewModels. When I initiate the viewmodel the observablecollections in both ViewModels work fine, but when I make changes in the source ObservableCollection it doesn't update it in the ObservableCollection in the second ViewModel. How can I make the second observalbeCollection receive the changes made in the first ObservableCollection.

VM 1

public Class VM1
{
    private ObservableCollection<CameraPackage> _cameraPackagesPerScene = new ObservableCollection<CameraPackage>();
    public ObservableCollection<CameraPackage> CameraPackagesPerScene
    {
        get { return _cameraPackagesPerScene; }
        set { _cameraPackagesPerScene = value; RaisePropertyChanged(); }
    }
 }

VM2

public Class VM2
{
     public ObservableCollection<CameraPackage> CameraPackagesPerSceneAndPartials { get; set; }

     public VM2 (VM1 vm1)
     {
           CameraPackagesPerSceneAndPartials = new ObservableCollection<CameraPackage>(vm1.CameraPackagesPerScene);
     }
 }

Upvotes: 0

Views: 883

Answers (2)

Igor Quirino
Igor Quirino

Reputation: 1195

You can use mvvmlight messenger to interchange messages from viewmodels.

This is a Nice way to do this. See the sample below:

SENDING:

// Sends a notification message with a Person as content.
var person = new Person { FirstName = "Marco", LastName = "Minerva" };
Messenger.Default.Send(new NotificationMessage<Person>(person, "Select"));

 RECEIVING:

// Registers for incoming Notification messages.
Messenger.Default.Register<NotificationMessage<Person>>(this, (message) =>
{
    // Gets the Person object.
    var person = message.Content;

    // Checks the associated action.
    switch (message.Notification)
    {
        case "Select":
            break;
        case "Delete":
            break;
        default:
            break;
    }
});

FROM TUTORIAL:

https://marcominerva.wordpress.com/2014/06/25/how-to-send-string-and-content-messages-with-mvvm-light-messenger/

Upvotes: 0

Vadim Martynov
Vadim Martynov

Reputation: 8892

You should not create new ObservableCollection based on other OC. Just share one instance to both ViewModels:

public VM2 (VM1 vm1)
{
      CameraPackagesPerSceneAndPartials = vm1.CameraPackagesPerScene;
}

Or inject only collection to the second ViewModel:

public VM2 (ObservableCollection<CameraPackage> cameraPackagesPerSceneAndPartials)
{
      CameraPackagesPerSceneAndPartials = cameraPackagesPerSceneAndPartials;
}

Other way to reduce the coupling is to using EventAggregator or other event-based patterns.

Upvotes: 1

Related Questions