MVVM light: Pass object from view to viewmodel

前端 未结 2 1421
迷失自我
迷失自我 2021-01-23 06:01

I \'ve recently started working with WPF using MVVM light and I have the following (simple scenario).

  1. MainWindow contains a listbox of elements.

2条回答
  •  长发绾君心
    2021-01-23 06:23

    I'm not a MVVM expert but when I want to navigate to a new view to show something after clicking on ListBox Item I send a new message within the object that I want to show in this new view, and then I navigate to. I'm writing this because I'm thinking that Your approach is a little bit intricate, however I'm a Windows Phone app developer so take this comment accordingly.

    Anyway, the first function of messages is to allow communication through viewmodels, so in my opinion you should register the message also in the ReservoirViewerViewModel and here get the Reservoir "attachment" using msg.Reservoir.

    In ReservoirViewerViewModel:

    private void RegisterMessages() 
    {
        Messenger.Default.Register(this, ReservoirReceived);
    }
    
    private void ReservoirReceived(LaunchShowReservoirMessage msg) {
        this.LocalReservoir = msg.Reservoir;
    }
    
    public Reservoir LocalReservoir { get... set... } ...
    

提交回复
热议问题