MVVM Light Messenger Action Executing Multiple Times

With MVVM Light you can get into a situation where you code-behind's message handler gets called multiple times.

If the ctor for the view is registering for a message then the every time the view loads another subscription will be added; then when the message is sent the are effectively 2 'listeners' which end up executing the registered Action method multiple times.

One solution to this is to make sure you un-register when the view unloads.

The example below shows the code-behind for a simple settings page that registers for a DialogMessage in the ctor, and un-registers when the page is done with.

    public partial class Settings : PhoneApplicationPage
    {
        public Settings()
        {
            InitializeComponent();
            Messenger.Default.Register<DialogMessage>(this, DialogMessageHandler);
        }
        private void DialogMessageHandler(DialogMessage message)
        {
            var result = MessageBox.Show(message.Content, message.Caption, message.Button);
            
            message.ProcessCallback(result);
        }
        private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e)
        {
            Messenger.Default.Unregister(this);
        }
    }

SHARE:

Add comment

Loading