locked
Best Method for Saving State of ComboBox

    Question

  • As a beginner, I am constructing a simple multi-page Windows Store App that has a comboBox populated with an ObservableDictionary. There must be a way of saving and loading the selected comboBox item using the NavigationHelper, so that the item reappears when navigating back to that page.  I'm having difficulty because there are only examples provided of saving and loading text strings into textblocks or textboxes.  Furthermore, it seems that the PageState key only saves strings and not other data types.  I've tried a few ways of converting the string, but none of my methods have worked, including:

            For navigationHelper_SaveState(object sender, SaveStateEventArgs e)...

                e.PageState["selectedItem"] = ComboBox.SelectedIndex;

           Then the corresponding navigationHelper_LoadState(object sender, SaveStateEventArgs e)

                ComboxBox.SelectedIndex = Convert.ToInt16(e.PageState.Values["selectedItem"]);

           Produced the compiler error "Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.Dictionary<string,object>.ValueCollection'

    Am I on the right track or even close?  What is the best practice? 

    Saturday, March 29, 2014 10:04 PM

Answers

  • Okay I made some progress by trial and error.  It works, but I doubt that my solution, shown below, wins any coding award.  The trick was the second to the last line where I change the variable type into "int". 

    private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
            // Restores selected saved value of ComboBox in previous session state
            {
                if (e.PageState != null && e.PageState.ContainsKey("selectedItem"))
                {
                    var passingSelectedValue = e.PageState["selectedItem"];
                    int SelectedValueAsInt = (int)passingSelectedValue;
                    ComboBox.SelectedIndex = SelectedValueAsInt;
                }
             }

    • Marked as answer by Dave90807 Sunday, March 30, 2014 3:56 AM
    Sunday, March 30, 2014 3:54 AM