mvvmmvvm-lightmvvm-toolkit

MVVM Light Messenger


I am new to MVVM Light and I am trying to learn and implement the Messenger class. I have read many other messenger tutorials and posts but still can't get it to work. Below is some code I wrote to help me learn. From my research I think I have everything implemented correctly but it does not work. Does anyone know what I am doing wrong?

public class MainViewModel : ViewModelBase
{
    public MainViewModel() { }  

    private RelayCommand _sendMessage;  
    public RelayCommand SendMessage
    {
        get
        {
            return _sendMessage
                ?? (_sendMessage = new RelayCommand(
                                      () =>
                                      {
                                          var pInfo = new PersonalInfo { Name = "Some Name", Age = 31 };
                                          Messenger.Default.Send(pInfo);                                            
                                      }));
        }
    }

} 

public class MessageReciever
{
    public MessageReciever()
    {          
        Messenger.Default.Register<PersonalInfo>(this,
            action =>
            {
                Debug.WriteLine(action.Age);
                Debug.WriteLine(action.Name);
            }
            );
    }    
}

public class PersonalInfo
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Solution

  • Try this:

    public class MainViewModel : ViewModelBase
    {
        MessageReciever mr = new MessageReciever();
    
        public MainViewModel() { }
    
        private RelayCommand _sendMessage;
        public RelayCommand SendMessage {
            get {
                return _sendMessage
                    ?? (_sendMessage = new RelayCommand(
                                          () =>
                                          {
                                              var pInfo = new PersonalInfoMessage(new PersonalInfo { Name = "Some Name", Age = 31 } );
                                              Messenger.Default.Send(pInfo);
                                          }));
            }
        }
    }
    
    public class MessageReciever
    {
        public MessageReciever() {
            Messenger.Default.Register<PersonalInfoMessage>(this,
                action =>
                {
                    Debug.WriteLine(action.Content.Age);
                    Debug.WriteLine(action.Content.Name);
                }
                );
        }
    }
    
    public class PersonalInfo
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    public class PersonalInfoMessage : GenericMessage<PersonalInfo>
    {
        public PersonalInfoMessage(PersonalInfo content)
            : base(content) {
        }
    }