I ‘ve recently started working with WPF using MVVM light and I have the following (simple scenario).
-
MainWindow contains a listbox of elements.
-
When one is selected and the button is clicked, I fire a command:
ReservoirViewerCommand.Execute(null); -
On the viewmodel class I instantiate the command and send a message with the selected object:
ReservoirViewerCommand = new RelayCommand(OpenReservoir); private void OpenReservoir() { Messenger.Default.Send(new LaunchShowReservoirMessage(){Reservoir=SelectedReservoir}); }where:
class LaunchShowReservoirMessage:MessageBase { public Reservoir Reservoir { get; set; } } -
The mainview registers the message and opens a new child window:
private void RegisterMessages() { Messenger.Default.Register<LaunchShowReservoirMessage>(this,OnLaunchShowReservoir); } public void OnLaunchShowReservoir(LaunchShowReservoirMessage msg) { var showReservoir = new ReservoirViewerView(); showReservoir.Show(); }
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.
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
In Xaml View
In Xaml Resources
Simply register for the same message in your ReservoirViewerViewModel class:
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:
And then: