Pass complex object between pages in C#

后端 未结 2 1401
广开言路
广开言路 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 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
    }
    

提交回复
热议问题