How to pass objects through multiple pages in UWP

微笑、不失礼 提交于 2019-12-11 17:49:37

问题


I am tasked with creating a multi-page UWP app that needs to pass a student object through multiple pages. The app starts on the main page where there are two buttons, one to add a new student and then and the other to then view the students details.

I am currently struggling trying to figure out how to pass the student object from the "new student page" to the "student details" page. I'm not allowed to store the students information in a file or database.

When a new student has been added the information should be stored within the Student object, is it possible to make this object public so that it can be used without passing it through pages? Is it also possible to bind the text blocks on the student details page to the student object that is from the input page?


回答1:


You can use your Student class object and then pass it to another page when Navigate to it as parameter.

In New Student page :

void ButtonShowDetails_Click(sender , ....)
{
  var student = new Student();
  student.Name="Joe";// or txtStudentName.Text
  /// etc
  /// etc
  Frame.Navigate(typeof(pgStudentDetails), student);
}

In pgStudentDetails page :

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    var param = (Student)e.Parameter; // get parameter
    txtName.Text= param.Name;//show data to user
}



回答2:


This isn't good way of resolving this problem.

You see… an expert developer sees the UI only as the "presentation layer" for app data, NOT as the main logic layer.

The correct way to do it is creating a static entity that acts as the "engine" of the logic of your app and that is present during all the app's session.

The usual way to implement this, in fact, is by using the standard MainPage as the "shell" of the app, containing a static field (named "Current") that redirects to the MainPage itself, and an AppViewModel class, that contains all the app data and logic. Then you access the MainPage.Current.ViewModel data by binding all the XAML controls to it.

Best regards



来源:https://stackoverflow.com/questions/53701560/how-to-pass-objects-through-multiple-pages-in-uwp

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