I am new to MVVMLight and have started to use it in my WP7 app. I have a View/page which registers for MessageDialogs and then my VM sends the message to show it. This works great. However, when you go back to the previous screen (with WP7 back button) and then enter the page again (using AppBar menu item) then the message fires twice (and increments every time you view the page). I assume it the View is registering every time and old versions are subscribing to the message, but I am not sure of how it should work.
I tried to call VM.Cleanup in my NavigatedFrom event to ensure the old messages are unregistered when they leave the page, but this did not help. Here is my code:
View:
public AboutPage()
{
InitializeComponent();
Messenger.Default.Register<DialogMessage>(this, msg => { var result = MessageBox.Show(msg.Content, msg.Caption, msg.Button); });
}
protected override void OnNavigatedFrom(NavigationEventArgs args)
{
ViewModelLocator.AboutViewModelStatic.Cleanup();
base.OnNavigatedFrom(args);
}
AboutViewModel: (Code gets fired by a command)
var message = new DialogMessage("Why does this fire multiple times?", DialogMessageCallback) { Button = MessageBoxButton.OK, Caption = "" };
Messenger.Default.Send(message);
That’s all there is too it, but each time you come to this page it fires once more… I assume it is something to do with Cleanup but I am not sure how it is supposed to work in WP7… any tips appreciated…
A view is created & destroyed as you navigate through the application. Therefore, in your AboutPage view’s constructor, the view is registering for the message every time it is created.
A better approach is to setup the registration in the ViewModel’s constructor, use a ViewModelLocator and databind the View to the ViewModel. The ViewModel is created once and used throughout the lifetime of the application. Jonas Follesoe’s FlightsNorway is good WP7 application to learn about MVVMLight, you can find the MVVMLight Messenger class being used very nicely.
HTH, indyfromoz