I'm having a problem to pass parameters betweeen my ViewModels using the Messenger class in the MVVMLight Framework.
This is the code I'm using :
ViewModelLocator
public ViewModelLocator ()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<INavigationService, NavigationService>();
SimpleIoc.Default.Register(() => new MainViewModel(NavigationService));
SimpleIoc.Default.Register(() => new SecondViewModel(NavigationService));
}
public MainViewModel MainViewModel
{
get { return SimpleIoc.Default.GetInstance<MainViewModel>(); }
}
public SecondViewModel SecondViewModel
{
get { return SimpleIoc.Default.GetInstance<SecondViewModel>(); }
}
public INavigationService NavigationService
{
get { return SimpleIoc.Default.GetInstance<INavigationService>(); }
}
MainViewModel
private void ShowPersonDetailsCommand(object obj)
{
Messenger.Default.Send((Person)obj);
_navigationService.NavigateTo(new Uri("/SecondPage.xaml", UriKind.Relative))
}
SecondViewModel
public SecondViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
Messenger.Default.Register<Person>(
this,
person =>
{
Person = person;
});
}
In my MainViewModel
(ShowPersonDetailsCommand), I'm navigating to a SecondPage and sending a person as parameter in the Messenger class. At this point, the person is well constructed and sent as a message.
But in the SecondViewModel
constructor, the person is null :(
Is there something I'm missing ?
I thinks I did something wrong ...
For your information :
Windows Phone 8.1 (Silverlight)
MVVMLight 5.0.2
Visual Studio 2013 Update 4
I would suggest creating the SecondViewModel
immediately as soon as it is registered in the ViewModelLocator
. You can do that by using a overloaded method of Register
.
SimpleIoc.Default.Register<SecondViewModel>(true);
This will make sure that ensure that the Messenger
registration happens before the message is sent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With