Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter between ViewModels using MVVMLight

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

like image 501
Wassim AZIRAR Avatar asked Dec 07 '14 19:12

Wassim AZIRAR


1 Answers

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.

like image 97
Sridhar Avatar answered Sep 20 '22 01:09

Sridhar