Search code examples
pivotwindows-phone-8.1winjs

How can you restore a pivot controls selectedIndex when navigating back using WinJS on Windows Phone 8.1?


I'm trying to restore the selectedIndex property of pivot control after a user navigates to a "detail page" and then back to the pivot page.

I'm capturing the selectedIndex and storing it in session state on the pivot pages unload event. What I've been unable to figure out is when to restore the value.

I've tried on the page load event. I've verified the value is being set, but it seems some other event is firing later and overwriting it.

I've tried checking if the session state variable is set in the pivots onselectionchanged and onitemanimationstart events, but setting it in either of those causes the app to crash. For the record the exception is: 0x80020101 - JavaScript runtime error. Could not complete the operation due to error 80020101.

var sessionState = WinJS.Application.sessionState;
var hub = null;

//in the WinJS.UI.Pages.Define call for the pivot item page
ready: function (element, options) {
    hub = element.querySelector(".hub").winControl;

    hub.onselectionchanged = function (args) {
       //crashes app
       if (sessionState.collectionItemSelectedIndex) {
           hub.selectedIndex = sessionState.collectionItemSelectedIndex;
       }

       //code omitted
    }

    //code omitted
},

unload: function () {
    sessionState.collectionItemSelectedIndex = hub.selectedIndex;
    console.log('pivot index: ' + sessionState.collectionItemSelectedIndex);
},

//This does fire, and does set the index, but it seems to be overwritten soon after
load: function (uri) {
    if (sessionState.collectionItemSelectedIndex) {
        hub.selectedIndex = sessionState.collectionItemSelectedIndex;
        console.log('pivot index: ' + sessionState.collectionItemSelectedIndex);
    }

    //taken from base.js
    if (!this.selfhost) {
        return WinJS.UI.Fragments.renderCopy(uri);
    }
},

Solution

  • So I've solved the problem.

    By setting the selected index in the onitemanimationstart event and setting it to null immediately after using it things are now working.

    It's slightly less than ideal however as when you navigate back to the pivot page you see the first pivot section for a moment, then it animates over to the section you left from. Does anybody know a better way to do this, one that won't display the first section for that brief moment?