1

About using messenger of mvvmlight v4, I have a questions: Where should we put the register of Messenger? I sought out some examples, they put them in constructor of view. But I got a problem with that, anytime we create an instance of view, this message is registered again --> the message handler will be invoked as the same number of registered message.

Such as: I register a message like:

Messenger.Default.Register<NotificationMessage>(this, (nm) =>
    {
        if (nm.Sender == this.DataContext)
        {
           if (nm.Notification == "OnNext")
           {
               this.Hide();
               Form2 f2= new Form2();
               f2.Show();
           }
        }
    }

--> Everytime, 1st time user clik Next, 1 form appears, but when user click Next again, this time, 2 messages were registered & make 2 forms appear. How can I handle this case?

Thanks in advance for any help of you.

kidgu
  • 413
  • 1
  • 8
  • 18
  • Luckily, I find the way to solve this issue: that is I unregister the message before I register. Like : Messenger.Default.Unregister(this);. Anyway, I'm still waiting for the comments from you to ensure that I did it right way. – kidgu Dec 10 '12 at 10:50

1 Answers1

2

The constructor of the view seems to be a good place to put the register of Messenger. You can put the unregister in the Cleanup() function (you have to implement the ICleanup interface)

public class MainWindow : ICleanup
{
    public MainWindow()
    {
        InitializeComponent();

        Messenger.Default.Register(recipient, action);
    }

    public void Cleanup()
    {
        Messenger.Default.Unregister(recipient, action);
    }
}
Romain
  • 121
  • 2
  • Hi, I did put the Unregister in deconstructor of the view, it seems to be not good & I got a trouble (http://stackoverflow.com/questions/13912718/unregister-message-in-destructor-make-error-handle-is-not-initialized/13913406#13913406). Thanks for your reply! – kidgu Dec 18 '12 at 02:15