更新Viewmodels之间的ObservableCollection

时间:2015-12-08 21:24:25

标签: c# wpf mvvm observablecollection

我在两个ViewModel之间共享了一个observableCollection。当我启动viewmodel时,两个ViewModel中的observablecollections工作正常,但是当我在源ObservableCollection中进行更改时,它不会在第二个ViewModel中的ObservableCollection中更新它。如何让第二个observalbeCollection接收第一个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);
     }
 }

2 个答案:

答案 0 :(得分:0)

您不应该基于其他OC创建新的ObservableCollection。只需将一个实例共享给两个ViewModel:

(?:contrib|donat|gifts)(?=[^\.]+\bto\b[^\.]+).*to\s([^\.]+)

或者只将集合注入第二个ViewModel:

array:indexCopy(1, indices, torch.Tensor({1, 2, 3}))

减少耦合的其他方法是使用EventAggregator或其他event-based patterns

答案 1 :(得分:0)

您可以使用mvvmlight messenger来交换来自视图模型的消息。

这是一个很好的方法。请参阅以下示例:

<强> 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"));

<强>接收

// 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/