2015-12-08 49 views
0

我在兩個ViewModels之間共享了一個observableCollection。當我啓動viewmodel時,兩個ViewModel中的observablecollections都能正常工作,但是當我在源ObservableCollection中進行更改時,它不會在第二個ViewModel中的ObservableCollection中更新它。我如何使第二個observalbeCollection接收在第一個ObservableCollection中所做的更改。在Viewmodels之間更新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); 
    } 
} 
+0

您不應該將ViewModels傳遞到其他ViewModel構造函數中,使測試變得更加困難,並使它們緊密耦合。考慮使用messager/messagebus/event aggregator來代替視圖之間的這種變化 – Tseng

+0

您是否使用任何mvvm框架? –

+0

@IgorQuirino我正在使用galasoft mvvmlight – Phil

回答

0

基於其他OC你不應該創建新的ObservableCollection。只是共用一個實例雙方的ViewModels:

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

或注入只收集到第二視圖模型:

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

其他的方式來降低耦合是使用EventAggregator或其他event-based patterns

0

您可以使用mvvmlight使者從的ViewModels交換消息。

這是一個很好的方法來做到這一點。請參見下面的示例:

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教程:

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