Reputation: 601
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
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:
Upvotes: 0
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