Skip to main content
 首页 » 编程设计

窗口之间的 C# 数据丢失

2024年02月13日11jpfss

为了导航我的应用程序,您会在加载时看到主窗口。您可以单击一个按钮来打开 TeacherTools 窗口。从这里您可以将新学生添加到列表中。在这个窗口上,我有一个后退按钮,可以让您返回到主窗口,我可以确认信息在这里仍然可用。我遇到了一个问题,我打开了第三个窗口,这是一个考试窗口,之后学生会在其中提出问题,他们的分数应该添加到当前加载的学生签证他的名字中。

private List<Student> studentList = new List<Student>(); 
 
public partial class MainWindow : Window 
{ 
    TeacherTools teachTools = new TeacherTools(); 
    Learning myLearning = new Learning(); 
 
    private void teachAdmin_Click(object sender, RoutedEventArgs e) 
    { 
        this.Hide(); 
        teachTools.ShowDialog(); 
        this.Show(); 
    } 
 
    private void Selection_Click(object sender, RoutedEventArgs e) 
    { 
        this.Hide(); 
        myTest.studentName.Text = studentsList.SelectedValue.ToString(); 
        myTest.ShowDialog(); 
        this.Show(); 
    } 
 
} 
 
//Exam Window 
public partial class Test : Window 
{ 
    //I'm sure its not this 
    Student loadedStudent = new Student(); 
    TeacherTools teachTools = new TeacherTools(); 
 
    public void(private void finishTest() 
    { 
 
        loadedStudent = teachTools.Kids.Find(delegate(Student s) { return s.Name == studentName.Text; }); //This line  
        loadedStudent.Attempted = true; 
        loadedStudent.Score = score; 
    } 
} 

因此我收到“未设置对象实例的对象引用。- NullReferenceException”。我不确定为什么会这样,因为我可以从 MainWindow 修改 Student 对象。

编辑:TeacherTools 类

public partial class TeacherTools : Window 
{ 
    private List<Student> studentList = new List<Student>(); 
 
    public TeacherTools() 
    { 
        InitializeComponent(); 
    } 
 
    public List<Student> Kids 
    { 
       get { return studentList; } 
       //set { studentList = value; } 
    } 
 
    private void newStudentClick(object sender, RoutedEventArgs e) 
    { 
        Student student = new Student(); 
        student.Name = nameBox.Text; 
        studentList.Add(student); 
        studentData.ItemsSource = studentList; 
        studentData.Items.Refresh(); 
        //nameBox 
    } 
} 

请您参考如下方法:

在名为“Test”的窗口中,您正在使用对象 teachTools 但您尚未在任何地方创建它。

您的 MainWindow 中确实有一个类似命名的对象,但它不与 Test-window 共享。您还应该在测试窗口中创建一个新实例