为了浏览我的应用程序,在加载时会显示Mainwindow。您可以单击一个按钮,以打开“教师工具”窗口。从这里,您可以将新学生添加到列表中。在此窗口上,我有一个后退按钮,它将使您返回MainWindow,并且可以确认此处的信息仍然可用。我遇到一个问题,我打开了第三个窗口,这是一个考试窗口,之后向学生显示问题,他们的分数应添加到当前加载的学生签证的名字中。

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窗口时,正在创建TeacherTools窗口的新实例,这意味着Kids列表中没有元素。如果这是您要完成此操作的方式,则可以在TeacherTools窗口中将Test实例设置为公共属性,然后从主窗口传递对象,如下所示:

//Test Window
public partial class Test : Window
{
    Student loadedStudent = new Student();
    public TeacherTools teachTools { get; set; }
    ...
}

//Main Window
public partial class MainWindow : Window
{
    ...

    private void Selection_Click(object sender, RoutedEventArgs e)
    {
        this.Hide();
        myTest.teachTools = this.teachTools;
        myTest.ShowDialog();
        this.Show();
    }
}


请注意,我尚未对此进行测试,但是我认为这是您正在寻找的方法。我还要说的是,通过在彼此之间传递不同的窗口而不是使用类来处理这个问题,您可能正在玩危险的游戏。

关于c# - Windows之间的C#数据丢失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16006382/

10-15 03:13