Pass complex object between pages in C#

一笑奈何 提交于 2019-12-20 06:36:18

问题


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.

private void quizbtn_Click(object sender, RoutedEventArgs e)
        {

            var sectorId = "Items1";

            this.Frame.Navigate(typeof(Quiz), sectorId);
        }

The Quiz page receives the passed parameter sectorId in the load page function where Object navigationParameter is the sectorId passed.

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

I want to make the object passed, that is, sectorId more complex so that it does not just include the string of text "Items1", but Includes the string of text, and index, and a value representing a total(int).

How do I pass this complex object and load it on the page?


回答1:


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
}



回答2:


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.



来源:https://stackoverflow.com/questions/20035668/pass-complex-object-between-pages-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!