MVVM light: Pass object from view to viewmodel

前端 未结 2 1481
迷失自我
迷失自我 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:36

    "I did some step-by-step debugging and the ViewModel constructor seems never to be reached."

    Make sure that you are actually binding your view to your view model using one of the following:

    In CodeBehind

    var showReservoir = new ReservoirViewerView();
    showReservoir.DataContext = ViewModelLocator.ReservoirViewerViewModel; //static property
    //OR showReservoir.DataContext = new ReservoirViewerViewModel();
    showReservoir.Show();
    

    In Xaml View

    
        
    
        
    
    

    In Xaml Resources

    
        
    
    

    "What I need is that the new ViewModel (ReservoirViewerViewModel) can somehow get hold of the passed object through the message so that I can then display the details of this object on the child window."

    Simply register for the same message in your ReservoirViewerViewModel class:

    Messenger.Default.Register(this, (msg) =>
    {
        var reservoir = msg.Reservoir;
    });
    

    FYI, if you derive your message class from GenericMessage<[content type]> instead of MessageBase, then you can use the already-defined Content property of the GenericMessage class. For example:

    public class LaunchShowReservoirMessage: GenericMessage
    {
        public LaunchShowReservoirMessage(Reservoir content) : base(content) { }
    }
    

    And then:

    Messenger.Default.Register(this, (msg) =>
    {
        var reservoir = msg.Content;
    });
    

提交回复
热议问题