views:

191

answers:

1

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.

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.

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:

    protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
    {
        Messenger.Default.Send<PhoneApplicationPage>(this);
        base.OnNavigatedFrom(e);
    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        Messenger.Default.Send<PhoneApplicationPage>(this); 
        base.OnNavigatedTo(e);
    }

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).

What is the most MVVM-Light friendly way to handle these events?

UPDATE: I was able to resolve the second issue by Sending the Messages like this:

    protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
    {
        Messenger.Default.Send<PhoneApplicationPage>(this,"NavigatedFrom");
        base.OnNavigatedFrom(e);
    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        Messenger.Default.Send<PhoneApplicationPage>(this, "NavigatedTo"); 
        base.OnNavigatedTo(e);
    }

and Registering them like this:

        Messenger.Default.Register<PhoneApplicationPage>(this, "NavigatedFrom", false, (action) => SaveState(action));
        Messenger.Default.Register<PhoneApplicationPage>(this, "NavigatedTo", false, (action) => RestoreState(action));
A: 

Looks like you have a solution to your problem already. I would also suggest the following:

Look at using one of the message values provided in the mvvm-toolkit, such as:

    NotificationMessage<T>

Like this:

    Messenger.Default.Send<NotificationMessage<PhoneApplicationPage>>(
new NotificationMessage<PhoneApplicationPage>(this, "Message"));
Ryan from Denver