Pass complex object between pages in C#

后端 未结 2 1389
广开言路
广开言路 2021-01-26 09:24

I am using this code to pass values in my Windows 8 app.

The following code passes data to a page when an item is clicked, So it passes sectorId to the Quiz page.

<
相关标签:
2条回答
  • 2021-01-26 09:41

    The Frame.Navigate method takes an object as a parameter, and really doesn't care what type of object it is. You can create any kind of object and pass it as the second parameter.

    public struct QuizArgs
    {
        public string Question;
        public string[] Answers;
        public int CorrectIndex;
        public DateTime Timestamp;
    }
    
    
    
    
    private void quizbtn_Click(object Sender, RoutedEventArgs e)
    {
        var args = new QuizArgs
        {
            Question = "What color is the sky?",
            Answers = new string[] { "Red", "Green", "Blue", "Silver" },
            CorrectIndex = 2,
            Timestamp = DateTime.Now
        };
    
        this.Frame.Navigate(typeof(Quiz), args);
    }
    

    And in your Quiz class:

    protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
    {
        if (navigationParameter == null)
            throw new ArgumentNullException("navigatyionParameter");
        QuizArgs args = navigationParameter as QuizArgs;
        if (args == null)
            throw new ArgumentException(string.Format("Incorrect type '{0}'", navigationParameter.GetType().Name), "navigationParameter");
    
        // Do something with the 'args' data here
    }
    
    0 讨论(0)
  • 2021-01-26 10:03

    Passing data between pages is usually done using the query-string (GET) or by using a form (POST). You cannot really pass a complex object between pages, unless you serialize it to a string first and then use the before mentioned methods (GET/POST), but that's not recommended due to length restrictions.

    However, you can use the session state and/or the application state to store complex objects (as long as they are serializable) and use them across different requests.

    0 讨论(0)
提交回复
热议问题