views:

214

answers:

1

Hi, I am using MVVM Light toolkit "Messenger" class-

A Messenger class (and diverse message types) to be used to communicate within the application. Recipients only receive the message types that they register for. Additionally, a target type can be specified, in which case the message will only be transmitted if the recipient's type matches the target parameter.

Specifically: public virtual void Send(TMessage message); where TMessage is string for Uri of a View / Page within application.

The method description indicates:

// Summary:
    Sends a message to registered recipients. **The message will reach all recipients
     that registered for this message type using one of the Register methods.**

 Parameters:
   message:
     The message to send to registered recipients.

 Type parameters:
   TMessage:
     The type of message that will be sent.

In my ViewModel code, I have something like this:

string viewuri = "/View/Page1.xaml";
Messenger.Default.Send(viewuri );

If I register to receive this message in View and try to navigate using something like:

NavigationService.Navigate(new Uri(viewuri, UriKind.Relative));

I get exception: A first chance exception of type 'System.InvalidOperationException' occurred in Microsoft.Phone.Controls.Navigation.dll

But, if I DONOT register to receive this message anywhere in code, then navigation work without any problem. Can someone please explain this to me? How is this message containing Uri handled by the system?

Thanks.

Update: Please see my comment below. I think there is some problem in my code, the way I am unregistering the messenger in view (MainPage). Register in ctor:

  public MainPage()
    {
        InitializeComponent();
        Messenger.Default.Register<string>(this, m => MessageHandler(m));
        SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

    }

Unregister in Messagehandler once message is received within MainPage Class:

      private void MessageHandler(string message)
    {
            NavigationService.Navigate(new Uri(message, UriKind.Relative));
            Messenger.Default.Unregister<string>(this, m => MessageHandler(m));
    }
+2  A: 

Unregister doesn't work because you're using an anonymous method (lambda expression). When you write an anonymous method, that creates a new method, so when you unregister with the same lambda expression, it is actually a different method, so Unregister doesn't find a match and doesn't remove the delegate.

Anyway, in that case you don't need an anonymous method at all, you can directly register MessageHandler as the handler:

Messenger.Default.Register<string>(this, MessageHandler);

...

Messenger.Default.Unregister<string>(this, MessageHandler);
Thomas Levesque
Thank you. Stupid me!
curiousone