title: Handling the OnNavigatedFrom / OnNavigatedTo events in the ViewModel
body: <p>I am trying to figure out a way for my ViewModel to handle saving or restore the page's state when the page is navigated From or To.</p>
  
  <p>The first thing I tried was to add an EventToCommand behavior to the page, but the events (OnNavigatedFrom and OnNavigatedTo) are declared protected and the EventToCommand does not see the events to bind to.</p>
  
  <p>Next I thought I would try using the Messenger class to pass a message to the ViewModel using code in the View's code behind:</p>
  
  <pre><code>protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
  {
      Messenger.Default.Send&lt;PhoneApplicationPage&gt;(this);
      base.OnNavigatedFrom(e);
  }
  
  protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  {
      Messenger.Default.Send&lt;PhoneApplicationPage&gt;(this); 
      base.OnNavigatedTo(e);
  }
  </code></pre>
  
  <p>But this seems to have two issues, first is having this code in the code behind page. Second, the ViewModel cannot tell the difference between the OnNavigatedFrom and the OnNavigatedTo events without having to create a set a wrapper classes for the PhoneApplicationPage object (see UPDATE below).</p>
  
  <p>What is the most MVVM-Light friendly way to handle these events?</p>
  
  <p>UPDATE:
  I was able to resolve the second issue by Sending the Messages like this:</p>
  
  <pre><code>protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
  {
      Messenger.Default.Send&lt;PhoneApplicationPage&gt;(this,"NavigatedFrom");
      base.OnNavigatedFrom(e);
  }
  
  protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  {
      Messenger.Default.Send&lt;PhoneApplicationPage&gt;(this, "NavigatedTo"); 
      base.OnNavigatedTo(e);
  }
  </code></pre>
  
  <p>and Registering them like this:</p>
  
  <pre><code>Messenger.Default.Register&lt;PhoneApplicationPage&gt;(this, "NavigatedFrom", false, (action) =&gt; SaveState(action));
  Messenger.Default.Register&lt;PhoneApplicationPage&gt;(this, "NavigatedTo", false, (action) =&gt; RestoreState(action));
  </code></pre>